Broadcast Intent & Broadcast Receiver

  当Android系统发生某种状况,必须通知所有程序进行处理时,例如电量不足等,可利用Broadcast Intent对象的功能来进行信息广播。

 运行机制包括两部:送出Intent对象的程序;监听广播信息的程序(Broadcast Receiver),其本省是一个类,必须继承BroadcastReceiver类,必须向系统注册,并指定要监听的广播信息。当该监听的广播消息被送出时,系统会启动所有监听该广播消息的Broadcast Receiver程序,并运行onReceive()方法。

Broadcast Receiver程序只有在Android系统运行其onReceive()方法是才处于有效状态,一旦运行完毕就有可能被移除,直到下次监听的广播消息出现才再次运行,所以类似比较耗时的thread的异步工作不适合在onReceive()中运行。

1、建立Intent对象,并指定要广播的消息。

   Intent it = new Intent("tw.android.MY_BROADCAST");
   it.putExtra("sender","Broadcast Receive~");//附带数据,数据放入Intent对象中
   //利用bundle对象存入Intent对象
   Bundle bundle = new Bundle();
   bundle.putString("sender","Broadcast Receive~");
   it.putExtras(bundle);
  

2、调用sendBroadcast()方法广播Intent对象。

  sendBroadcast(it);

3、新建一个继承Broadcast Receiver类的新类,需要实现onReceive()方法。

public class myBroadcast extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
                //实现当监听的广播消息出现时要运行的方法,其中Intent对象是onReceive()的自变量,无需调用getIntent()来取得
               String sender = intent.getExtras().getString("sender");
	}

} 

4、在主程序中向Android系统注册上步中建立的Broadcast Receiver,以及要监听的广播消息。

在程序项目中的AndroidManifest.xml中注册:

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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=".myBroadcast"
            android:label="@string/app_name">
            <intent-filter >
                <action android:name="tw.android.MY_BROADCAST"/>
            </intent-filter>
        </receiver>
    </application>

  在程序中注册和取消注册:

	      IntentFilter itFilter = new IntentFilter("tw.android.MY_BROADCAST");
	      myBroadcast mybroadcast = new myBroadcast();
	      registerReceiver(mybroadcast,itFilter);
              ...
              unregisterReceiver(mybroadcast);//取消注册

  只有在程序中注册下能取消。

原文地址:https://www.cnblogs.com/ghimtim/p/4760444.html