美文网首页
【9】BroadcastReceiver

【9】BroadcastReceiver

作者: 嗟嗟嗟 | 来源:发表于2016-06-05 21:00 被阅读0次

一、什么是BroadcastReceiver

广播接收器,顾名思义,是用来接收广播的一个安卓组件,可用来在不同应用和组件之间传递消息。

二、广播接收器的注册

广播接收器必须通过注册才能使用,注册方法分为两种:

  • 静态注册
    在Manifests中进行
<receiver android:name=".MyBroadcastReceiver01">
    <intent-filter>
        <action android:name="BC_ONE"/>
    </intent-filter>
</receiver>
  • 动态注册
    在java代码中进行
IntentFilter intentFilter = new IntentFilter("BC_ONE");
MyBroadcastReceiver02 myBroadcastReceiver02 = new MyBroadcastReceiver02();
registerReceiver(myBroadcastReceiver02,intentFilter);
unregisterReceiver(myBroadcastReceiver02);//解除注册

ps:动态注册需要解除注册

不同的广播接收器通过action中的不同关键字来区分接受不同的广播。

三、广播的分类

广播接收器要接受广播,需要有广播发送方法,广播发送方法在content类中,可以通过intent来传递信息。

广播放松方式分为三类:

  1. 普通广播
  2. 有序广播
  3. 异步广播(已被弃用)
  • 普通广播:又称为无序广播,对相同优先级的接收器是随机顺序先后到达的,因此无法截断广播和在不同接收器间传递消息。
Intent intent1 = new Intent();
intent1.putExtra("msg","这是一条普通广播");
intent1.setAction("BC_ONE");
sendBroadcast(intent1);
  • 有序广播:广播接收器可按先后顺序接受此类广播,接受顺序为:动态注册高优先级接收器>动态注册低优先级接收器>静态注册优先级接收器>静态注册低优先级接收器,因此可以用abortBroadcast()方法截断广播,或者通过intent或者budle类来在不同接收器之间传递消息。
Intent intent2 = new Intent();
intent2.putExtra("msg","这是一条有序广播");
intent2.setAction("BC_ONE");
sendOrderedBroadcast(intent2,null);//第二个参数是接受权限

相关文章

网友评论

      本文标题:【9】BroadcastReceiver

      本文链接:https://www.haomeiwen.com/subject/ugerdttx.html