Android Broadcast广播

广播从注册方式上分为两种,静态广播和动态广播;从发送方式上也分为两种,无序广播和有序广播。
广播接收器的onReceive方法不应该执行较复杂的任务,否则会出错。一般是用于调用其他任务或显示一条通知。
在Activity onDestroy时,要解除注册接收器。

注册方式

静态广播

编写好广播接收器的实现类后,在AndroidManifest.xml中添加

<receiver
    android:name=".MyReceiver"
    android:enabled="true" <!-- 启用 -->
    android:exported="true"> <!-- 可接收外部广播 -->
    <intent-filter>
        <action android:name="balalala"/> <!-- 过滤器 -->
    </intent-filter>
</receiver>

注意:在较新版本的Android中,静态注册的广播无法接收广播。在发送广播时,必须用intent的ComponentName属性指定广播接收器的类全路径。

动态广播

编写好广播接收器的实现类后,在需要开启接收广播的Activity中调用registerReceiver(BroadcastReceiver)注册广播。

发送方式

无序发送

直接使用sendBroadcast(intent)发送广播。所有注册的接收器都将接收到这个广播。

顺序发送

会根据优先级从大到小依次链式接收广播,优先级大的接收器可以将广播中断(abortBroadcast()),广播就到此为止。

定义优先级

  1. 静态注册时
  2. 动态注册时filter.setPriority(888);

发送有序广播

    sendOrderedBroadcast(intent,true);

添加信息给低优先级的接收器、接收高优先级传来的消息

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle b= getResultExtras(true);
        setResultExtras(new Bundle());
    }

中止广播

    @Override
    public void onReceive(Context context, Intent intent) {
        abortBroadcast();
    }

猜你喜欢

转载自www.cnblogs.com/pravez/p/12621452.html