MianActivity
public class MainActivity extends AppCompatActivity { public static final String ACTION = "ordered_broadcast_action"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } // 发送广播 public void sendBroadcast(View view) { Intent intent = new Intent(ACTION); intent.putExtra("msg", "广播内容"); // 发送有序广播 sendOrderedBroadcast(intent, null); } }
FirstReceiver(接收器代表)
public class FirstReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String msg = intent.getStringExtra("msg"); Log.d("1622", "第一个接收器接到的数据:" + msg); } }
SecondReceiver(注意里面的中断方法)
public class SecondReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String msg = intent.getStringExtra("msg"); Log.d("1622", "第二个接收器接到的数据:" + msg); // 中断有序广播的传递 abortBroadcast();//广播顺序播放到这的时候将不再向下播放. } }
清单文件(确定优先级,如果没有优先级按书写顺序发送)
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.mobiletrain.android22_orderedbroadcast"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".activity.MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=".receiver.FirstReceiver"> <intent-filter android:priority="1"> <action android:name="ordered_broadcast_action"/> </intent-filter> </receiver> <receiver android:name=".receiver.SecondReceiver"> <intent-filter android:priority="2"> <action android:name="ordered_broadcast_action"/> </intent-filter> </receiver> <receiver android:name=".receiver.ThirdReceiver"> <intent-filter android:priority="3"> <action android:name="ordered_broadcast_action"/> </intent-filter> </receiver> </application> </manifest>
文章来源: 有序广播