BroadcastReceiver
继承BroadcastReceiver
public MyBroadcastReceiver extends BroadcastReceiver{
private static String TAG="MyBroadcastReceiver";
public void onReceive(Context context,Intent intent){
String msg = intent.getString("msg");//获取随广播而来的Intent中的数据
Log.i(TAG,msg);
}
}
广播注册
静态注册
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.intent.action.MY_BROADCAST"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
动态注册 (不是常驻型)
通常是在Activity或Service注册一个广播
MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver ();
IntentFilter filter=new IntentFilter();
filter.addAction("android.intent.action.MY_BROADCAST");
registerReceiver(receiver,filter);
//当这个Activity或Service被销毁时如果没有解除注册,系统会报一个异常,提示我们是否忘记解除注册了。
//解除注册
protected void onDestory(){
super.onDestory();
unregisterReceiver(receiver);
}
发送广播
public void send(View view){
Intent intent=new Intent("android.intent.action.MY_BROADCAST");
intent.putExtra("msg","hello receiver");
sendBroadcast(intent);
}
终止广播
abortBroadcast();
普通广播
普通广播对于多个接收者来说是完全异步的,通常每个接收者都无需等待即可接收到广播。对于这种广播,接收者无法终止广播,即无法阻止其他接收者的接收动作。
有序广播 (Ordered Broadcast)
有序广播比较特殊,它每次只发送到优先级较高的接收者那里,然后由优先级高的接受者再传播到优先级低的接受者那里,优先级高的接收者有能力终止这个广播。
<intent-filter android:priority="1000" //1000的优先级 范围 -1000到1000,数值越大,优先级越高。
<receiver>
<intent-filter android:priority="1000">
<action android:name="android.intent.action.MY_BROADCAST"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
public void send(View view){
Intent intent=new Intent("android.intent.action.MY_BROADCAST");
intent.putExtra("msg","hello receiver");
sendOrderedBroadcast(intent,"scott.permission.MY_BROADCAST_PERMISSION");
}
注意:
使用sendOrderedBroadcast方法发送有序广播时,需要一个权限参数,如果为null则表示不要求接收者声明指定的权限,如果不为null,则表示接收者若要接收此广播,需声明指定权限。这样做是从安全角度考虑的。
在AndroidMainfest.xml中定义一个权限:
<permission android:protectionLevel="normal"
android:name="scott.permission.MY_BROADCAST_PERMISSION"/>
声明权限
<uses-permission android:name="scott.permission.MY_BROADCAST_PERMISSION"/>
#setResultExtras(bundle);
setResultExtras(bundle); //将一个Bundle对象设置为结果集对象,传递到下一个接收者(多个接收者,有序广播)那里。这样以来,优先级低的接受者可以用getResultExtras获取到最新的经过处理的信息集合。