现在的位置: 首页 > 综合 > 正文

广播的发送与接收

2018年02月08日 ⁄ 综合 ⁄ 共 2032字 ⁄ 字号 评论关闭

发送端:

步骤1:发送自定义广播www.mycation.com,并附带数据

package com.example.send_1;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

	private static String MY_ACTION = "www.mycation.com";
	private Button m_btnSend;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        m_btnSend = (Button)findViewById(R.id.button1);
        m_btnSend.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setAction(MY_ACTION);
				intent.putExtra("msg", "消息数据");
				sendBroadcast(intent);
			}
        });
    }
}

接收端:

接收端定义接收该类型广播:www.mycation.com。并定义响应的类MyReceive_1

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.receive_1"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.receive_1.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name="MyReceive_1">
            <intent-filter>
                <action  android:name="www.mycation.com"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>

定义响应类的操作:类似弹出消息或重新启动某activity

package com.example.receive_1;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;


public class MyReceive_1 extends BroadcastReceiver{
	@Override
	public void onReceive(Context content, Intent intent) {
        String msg = intent.getStringExtra("msg");
        // 使用Toast显示
        Toast.makeText(content, "public class MyReceive_1 extends BroadcastReceiver" +
        msg, 
        Toast.LENGTH_LONG).show();
	}
}

其他的:

其实最主要的用途还是接收与发送均在一个apk内,或者响应系统广播。

内部使用,需要加static

抱歉!评论已关闭.