BroadcastReceiver:
BroadcastReceiver(广播接收器)是Android中的四大组件之一,用来通知某些事件的相关信息,如下载完成,设置改变等。
默认的BroadcastReceiver状态(新建完未更改任何设置)的简单使用方法:
1.通过new Intnet(MainActivity.this,MyReceiver.class)来启动指明的广播对象,(当manifests中注册了此BroadcastReceiver才能通过这种方法启动)
2.Intent可以通过intent.putExtra()方法携带一些信息,将这些信息传递给Broadcast
启动代码:
Intent i = new Intent(MainActivity.this,MyReceiver.class); i.putExtra("data","testing"); sendBroadcast(i);
动态注册和注销:
在新建BroadcastReceiver时,IDE默认在manifests文件中给BroadcastReceiver注册,当manifests文件中删除了它的注册信息的时候,可以在BroadcastReceiver中添加public static final action = "包名.Intent.action.actionName"),然后通过new Intent(BroadcastReceiverName.action)来启动未注册的BroadcastReceiver)。
注册方法:
//在BroadcastReceiver中需要添加,用于启动BroadcastReceiver
public static final String action = "程序包名.intent.action.MyReceiver";
//此注册方法的代码在Activity中
private MyReceiver receiver = null; if (receiver==null){ receiver = new MyReceiver(); registerReceiver(receiver,new IntentFilter(MyReceiver.action)); }
注销方法:
if (receiver!=null){ unregisterReceiver(receiver); receiver = null; }
同时向多个BroadcastReceiver发送信息的方法:
1.在manifests文件中为需要同时发送的BroadcastReceiver注册相同的启动action
2.通过Intent启动多个BroadcastReceiver相同的action,并向其发送信息,即能是所有相同action的BroadcastReceiver收到信息
manifests模块的注册代码:
<receiver android:name=".MyReceiver1" android:enabled="true" android:exported="true"> <intent-filter>
//设置的action <action android:name="程序包名.intent.action.MyReceiver"/> </intent-filter> </receiver>
<receiver android:name=".MyReceiver"> <intent-filter>
//设置的action <action android:name="程序包名.intent.action.MyReceiver"/>
</intent-filter>
</receiver>
//启动代码同注册时
BroadcastReceiver的优先级和中断操作:
BroadcastReceiver在未设置优先级的时候,同时发送信息的话,先在manifests文件中注册的BroadcastReceiver先收到信息,若是设置了优先级信息,那么优先级数值越大,优先级越高,优先级越高就先执行。
注:优先级在manifests文件中设置
在manifests文件中设置优先级的代码:
<receiver android:name=".MyReceiver1" android:enabled="true" android:exported="true"> <intent-filter android:priority="9"> //设置MyReceiver1的优先级为9 <action android:name="andrew.com.broadcastreceiverdemo.intent.action.MyReceiver"/> </intent-filter>
</receiver>
<receiver android:name=".MyReceiver">
<intent-filter android:priority="10"> //设置MyReceiver的优先级为10 <action android:name="andrew.com.broadcastreceiverdemo.intent.action.MyReceiver"/> </intent-filter>
</receiver>
//在设置对应的优先级后,MyReceiver会先接收到信息
BroadcastReceiver的中断操作:
在BroadcastReceiver存在接收优先级的时候,先接收到信息的BroadcastReceiver可以选择中断此广播,让优先级低于自己的BroadcastReceiver无法再接收到此次广播。
中断广播继续传递的代码:
@Override public void onReceive(Context context, Intent intent) { abortBroadcast(); //在这里中断此次广播 }
注:
若是有中断广播的操作,那么启动广播传递的方式不能是sendBroadcast()方法,使用sendBroadcast()发送的广播在接收时被中断,程序会出现错误。
要使中断广播的操作正常运行,需要使用sendOrderedBroadcast()方法。