第一行代码-5.3 发送自定义广播

1、发送标准广播
  这里实现的就是自定义广播接收器、静态注册广播以及发送广播

// MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mButton = (Button) findViewById(R.id.send_broadcast_button);
    mButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Intent intent = new Intent();
            intent.setAction("static_broadcast");
            sendBroadcast(intent);
        }
    });
}
// MyBroadcastReceiver.java
public class MyBroadcastReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "成功接收到静态注册广播", Toast.LENGTH_LONG).show();
    }

}

        <receiver android:name="com.example.broadcasttest.MyBroadcastReceiver">
            <intent-filter >
                <action android:name="static_broadcast"/>
            intent-filter>
        receiver>

第一行代码-5.3 发送自定义广播_第1张图片

2、发送有序广播
  首先创建新工程BroadcastTest2,然后也定义广播接收器,并静态注册。要注意的地方是在Manifest里,设置的intent-filter里面的action的名字必须要和前一个工程一样,才能让新的工程也接收到第一个工程发送的广播。
第一行代码-5.3 发送自定义广播_第2张图片
  到这里虽然两个应用都可以接收到广播,但方式是标准广播,每一个应用几乎同时接收到广播,无法截断,要改成有序广播,并设置优先级才可以截断。
  下面修改BroadcastTest中的代码:

mButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent();
                intent.setAction("static_broadcast");
                //sendBroadcast(intent);
                sendOrderedBroadcast(intent, null); // 发送有序广播
            }
        });

  然后修改BroadcastTest2中接收广播的优先级

<receiver android:name="com.example.broadcasttest2.AnotherBroadcastReceiver">
            <intent-filter android:priority="1">
                <action android:name="static_broadcast"/>
            intent-filter>
        receiver>

  最后在AnotherBroadcastReceiver中阻断广播:

public class AnotherBroadcastReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "BroadcastTest2接收到静态注册的广播!", Toast.LENGTH_LONG).show();
        abortBroadcast();
    }
}

  注意:系统注册的广播,优先级是从-1000到1000,而静态注册的广播的优先级可以从Integer.MIN到Integer.MAX。
  最终效果就是发送广播之后只有第二个应用可以接收到广播。

你可能感兴趣的:(Android)