有序广播可以按一定的优先级进行传播
首先进行发送广播
public void click(View v){ Intent intent = new Intent(); intent.setAction("com.coderwei.orderbroadcast"); sendOrderedBroadcast(intent,null,new FinalReceiver(),null,1,"我是一条有序广播",null); }
上面new FinalReceiver继承于与BroadcastReceiver,但是不用再清单文件中配置,有特权,可以用于接收最后的结果
public class FirstBroadcast extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String content = getResultData(); Toast.makeText(context,"First"+content,Toast.LENGTH_SHORT).show(); setResultData("我是一条已经被接收过一次了的有序广播"); } } public class SecondBroadcast extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String content = getResultData(); //abortBroadcast();//停止广播 Toast.makeText(context,"Second"+content,Toast.LENGTH_SHORT).show(); setResultData("我是一条被接收过两次的广播"); } } public class ThirdBroadcast extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String content = getResultData(); Toast.makeText(context,"Third"+content,Toast.LENGTH_SHORT).show(); } }
然后就是配置Manifest.xml
<receiver android:name=".FirstBroadcast"> <intent-filter android:priority="1000"> <action android:name="com.coderwei.orderbroadcast"/> </intent-filter> </receiver> <receiver android:name=".SecondBroadcast"> <intent-filter android:priority="800"> <action android:name="com.coderwei.orderbroadcast"/> </intent-filter> </receiver> <receiver android:name=".ThirdBroadcast"> <intent-filter android:priority="200"> <action android:name="com.coderwei.orderbroadcast"/> </intent-filter> </receiver>
android:priority 代表优先级,-1000 到 1000之间,数值越大,优先级越大。