Android

广播接收者(BroadcastReceiver)

2017-09-22  本文已影响55人  ProZoom

广播接收者(BroadcastReceiver)

1.定义广播接受者

静态注册广播

动态注册广播


2.发送广播

无序广播

无序广播发送方法

void sendBroadcast (Intent intent, String receiverPermission)

参数:

intent The Intent to broadcast; 传给接收者的意图 all receivers matching this Intent will receive the broadcast.所有匹配的广播接受者都回收到这一意图

receiverPermission (optional)可选的 String naming a permission that a receiver must hold in order to receive your broadcast.一个接收者必须拥有的权限 If null, no permission is required. 如果为null,则没有要求

示例:

sendBroadcast(intent, null);

有序广播

abortBroadcast()  
getResultExtras(true).putString("data", "新增数据");
<receiver android:name="com.top.myreceiver.MyReceiver1" >
     <intent-filter android:priority="1000">
         <action android:name="com.top.mybroadcast.xxx" />
     </intent-filter>
</receiver>

<receiver android:name="com.top.myreceiver.MyReceiver2" >
    <intent-filter android:priority="500">
      <action android:name="com.top.mybroadcast.xxx"/>
    </intent-filter>
</receiver>
        
<receiver android:name="com.top.myreceiver.MyReceiver3" >
    <intent-filter android:priority="100">
         <action android:name="com.top.mybroadcast.xxx" />
    </intent-filter>
</receiver>

void sendOrderedBroadcast (Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)

参数
intent* The Intent to broadcast; 传给接收者的意图 all receivers matching this Intent will receive the broadcast.所有匹配的广播接受者都回收到这一意图

receiverPermission (optional)可选的 String naming a permission that a receiver must hold in order to receive your broadcast.一个接收者必须拥有的权限 If null, no permission is required. 如果为null,则没有要求

resultReceiver Your own BroadcastReceiver to treat as the final receiver of the broadcast. 指定一的广播的最终接受者(必须执行的)
scheduler A custom Handler with which to schedule the resultReceiver callback;指定你的接收者回掉的handler; if null it will be scheduled in the Context's main thread. 如果为空,则默认为主线程
initialCode An initial value for the result code.初始的结果码 Often Activity.RESULT_OK. 通常设置

initialData An initial value for the result data.初始的结果数据 Often null. 通常为null

initialExtras An initial value for the result extras.初始化附加信息bundle; Often null通常为null

示例

Intent intent = new Intent("com.top.broadcast.TEST");         // 创建意图对象, 设置广播的动作
intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); // 广播是否启动那些没有启动过的应用
intent.putExtra("data", "最初的数据!!!");                                  // 这里的数据不会被修改
Bundle bundle = new Bundle();
bundle.putString("name", "张三");
sendOrderedBroadcast(intent, "com.top.permission.BROADCAST", new ResultReciever(), null, 1, "MainActivity", bundle);

短信黑名单

自动IP拨号

广播接收者生命周期 Broadcast receiver lifecycle

在android系统里面有很多内置的广播事件

上一篇 下一篇

猜你喜欢

热点阅读