有序广播可以按一定的优先级进行传播
首先进行发送广播
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,但是不用再清单文件中配置,有特权,可以用于接收最后的结果
1 public class FirstBroadcast extends BroadcastReceiver { 2 @Override 3 public void onReceive(Context context, Intent intent) { 4 String content = getResultData(); 5 Toast.makeText(context,"First"+content,Toast.LENGTH_SHORT).show(); 6 setResultData("我是一条已经被接收过一次了的有序广播"); 7 8 } 9 } 10 11 12 public class SecondBroadcast extends BroadcastReceiver { 13 @Override 14 public void onReceive(Context context, Intent intent) { 15 String content = getResultData(); 16 //abortBroadcast();//停止广播 17 Toast.makeText(context,"Second"+content,Toast.LENGTH_SHORT).show(); 18 setResultData("我是一条被接收过两次的广播"); 19 } 20 } 21 22 23 24 public class ThirdBroadcast extends BroadcastReceiver { 25 @Override 26 public void onReceive(Context context, Intent intent) { 27 String content = getResultData(); 28 Toast.makeText(context,"Third"+content,Toast.LENGTH_SHORT).show(); 29 30 } 31 }
然后就是配置Manifest.xml
1 <receiver android:name=".FirstBroadcast"> 2 <intent-filter 3 android:priority="1000"> 4 <action android:name="com.coderwei.orderbroadcast"/> 5 </intent-filter> 6 </receiver> 7 <receiver android:name=".SecondBroadcast"> 8 <intent-filter 9 android:priority="800"> 10 <action android:name="com.coderwei.orderbroadcast"/> 11 </intent-filter> 12 </receiver> 13 <receiver android:name=".ThirdBroadcast"> 14 <intent-filter 15 android:priority="200"> 16 <action android:name="com.coderwei.orderbroadcast"/> 17 </intent-filter> 18 </receiver>
android:priority 代表优先级,-1000 到 1000之间,数值越大,优先级越大。