Broadcast 广播使用详解
和你一起终身学习,这里是程序员Android
经典好文推荐,通过阅读本文,您将收获以下知识点:
一、Broadcast概述
二、Broadcast的注册
三、Broadcast的注册类型
四、静态注册开机广播的实现
五、动态监听亮灭屏幕广播实现
六、广播的发送方法
七、参考文献
一、Broadcast概述
在了解广播之前,我们先了解Broadcast
继承关系 ,
Broadcast
的继承关系如下:
java.lang.Object↳ android.content.BroadcastReceiver
Broadcast
是 Android
四大组件之一,是一种广泛运用在应用程序之间异步传输信息的机制。Broadcast
本质上是一个Intent
对象,差别在于Broadcast
可以被多个 BroadcastReceiver
处理。BroadcastReceiver
是一个全局监听器,通过它的 onReceive()
可以过滤用户想要的广播,进而进行其它操作。
BroadcastReceiver
默认是在主线程中执行,如果onReceiver()
方法处理事件超过10s
,则应用将会发生ANR(Application Not Responding)
,此时,如果建立工作线程并不能解决此问题,因此建议:如处理耗时操作,请用 Service
代替。
BroadcastReceiver
的主要声明周期方法onReceiver()
,此方法执行完之后,BroadcastReceiver
实例将被销毁。
二、Broadcast的注册
Broadcast
属于Android
四大组件之一,必须在Androidmainfest.xml
中注册.
Broadcast
注册方法如下:
<receiverandroid:name="ReceiverMethod"android:enabled="true"android:exported="true"><intent-filter><action android:name="String....." /></intent-filter></receiver>
注意:
如不注册,将导致无法接收处理广播消息
三、Broadcast的注册类型
广播的注册分两种(静态注册、动态注册),一种在Androidmainfest.xml
中静态注册,另一种是在Java
代码中动态注册。
1.静态注册
一些系统发送的广播需要在Androidmainfest.xml
中静态注册,例如 开机广播,apk状态改变广播,电量状态改变广播等。这些静态注册的广播,通常在Androidmainfest.xml
中拦截特定的字符串。
静态注册广播的方法如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.programandroid"android:versionCode="1"android:versionName="1.0" >... ...<receiverandroid:name="com.programandroid.BroadcastReceiver.NotificationReceived"android:enabled="true"android:exported="true" ><intent-filter><action android:name="Notification_cancel" /><action android:name="Notification_music_pre" /><action android:name="Notification_music_play" /><action android:name="Notification_music_next" /></intent-filter></receiver>... ...
2.动态注册广播
在Java中动态注册广播,通常格式如下:
//动态注册广播registerReceiver(BroadcastReceiver, IntentFilter);
四、静态注册开机广播的实现
1. 静态开机广播实现
p ublic class BootReceiverMethod extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {// 接收开机广播处理事情,比如启动服务Intent mStartIntent = new Intent(context, StartServiceMethods.class);context.startService(mStartIntent);}
}
2.静态注册开机广播
<!-- 必须声明接收开机广播完成的权限--><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /><receiverandroid:name=".component.BroadcastReceiver.BootReceiverMethod"android:enabled="true"android:exported="true"><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED" /></intent-filter></receiver>
五、动态监听亮灭屏幕广播实现
1.动态注册亮灭屏实现
动态注册广播方法是registerReceiver()
。
注意:
在广播中动态注册广播请注意一定要使用context.getApplicationContext()
,防止context
为空 ,引起空指针异常。
动态注册亮灭屏实现实现如下:
public class ScreenOnOffReceiver {public static void ReceiverScreenOnOff(Context context) {IntentFilter screenOffFilter = new IntentFilter();screenOffFilter.addAction(Intent.ACTION_SCREEN_OFF);screenOffFilter.addAction(Intent.ACTION_SCREEN_ON);BroadcastReceiver mScreenOnOffReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stubString action = intent.getAction();if (action.equals(Intent.ACTION_SCREEN_OFF)) {Toast.makeText(context, "接收屏幕熄灭广播", Toast.LENGTH_SHORT).show();}if (action.equals(Intent.ACTION_SCREEN_ON)) {Toast.makeText(context, "接收屏幕点亮广播", Toast.LENGTH_SHORT).show();}}};/*** context.getApplicationContext()* 在广播中注册广播时候需要注意,防止context 为空 ,引起空指针异常* **/
// 2.动态注册广播的方法context.registerReceiver(mScreenOnOffReceiver, screenOffFilter);}
}
六、广播的发送方法
广播的方法有以下三种:
1.无序sendBroadcast(intent)
2.有序sendOrderedBroadcast()
3.持续sendStickyBroadcast())
1.发送无序广播的方法
发送无序广播在Android
中很常见,是一种一对多的关系,主要通过 sendBroadcast(intent);
发送广播。
1.发送自定义广播案例
广播说白了就是一个带Action
等字符串标记的Intent
。发送自定义广播举例如下:
Intent customIntent=new Intent();customIntent.setAction("SendCustomBroadcast");sendBroadcast(customIntent);
2.接收自定义广播的方法
当用户对某些广播感兴趣的话,此时可以获取此广播,然后在onReceive
方法中处理接收广播的一下操作。
public class CustomBroadcast extends BroadcastReceiver {public CustomBroadcast() {}@Overridepublic void onReceive(Context context, Intent intent) {if (intent.getAction().equals("SendCustomBroadcast")){Toast.makeText(context,"自定义广播接收成功:Action:SendCustomBroadcast",Toast.LENGTH_SHORT).show();}}
}
注意
自定义广播是在Androidmanfest.xml
中静态注册的。
2.发送有序广播
广播在Android
是有优先级的,优先级高的广播可以终止或修改广播内容。发送有序广播的方法如下sendOrderedBroadcast(intent,"str_receiver_permission");
1.发送自定义有序广播
Intent customOrderIntent=new Intent();customOrderIntent.setAction("SendCustomOrderBroadcast");customOrderIntent.putExtra("str_order_broadcast","老板说:公司每人发 10 个 月饼");sendOrderedBroadcast(customOrderIntent,"android.permission.ORDERBROADCAST");
广播属于四大组件,一定要在AndroidMainfest.xml
中注册。
有序广播静态注册
接收有序广播的静态注册方法如下:
<receiverandroid:name=".component.BroadcastReceiver.CustomHightBrodcast"android:enabled="true"android:exported="true"><intent-filter android:priority="1000"><action android:name="SendCustomOrderBroadcast" /></intent-filter></receiver><receiverandroid:name=".component.BroadcastReceiver.CustomMiddleBroadcast"android:enabled="true"android:exported="true"><intent-filter android:priority="500"><action android:name="SendCustomOrderBroadcast" /></intent-filter></receiver><receiverandroid:name=".component.BroadcastReceiver.CustomLowerBroadcast"android:enabled="true"android:exported="true"><intent-filter android:priority="100"><action android:name="SendCustomOrderBroadcast" /></intent-filter></receiver>
有序广播处理,高优先级广播可以优先处理
public class CustomHightBrodcast extends BroadcastReceiver {public CustomHightBrodcast() {}@Overridepublic void onReceive(Context context, Intent intent) {if (intent.getAction().equals("SendCustomOrderBroadcast")) {Toast.makeText(context, intent.getStringExtra("str_order_broadcast"), Toast.LENGTH_SHORT).show();Bundle bundle=new Bundle();bundle.putString("str_order_broadcast","经理说:公司每人发 5 个 月饼");
// 修改广播传输数据setResultExtras(bundle);}}
}
中优先级的广播后序处理
public class CustomMiddleBroadcast extends BroadcastReceiver {public CustomMiddleBroadcast() {}@Overridepublic void onReceive(Context context, Intent intent) {if (intent.getAction().equals("SendCustomOrderBroadcast")) {Toast.makeText(context, getResultExtras(true).getString("str_order_broadcast"), Toast.LENGTH_SHORT).show();Bundle bundle=new Bundle();bundle.putString("str_order_broadcast","主管说:公司每人发 2 个 月饼");setResultExtras(bundle);}}
}
低优先级广播最后处理
public class CustomLowerBroadcast extends BroadcastReceiver {public CustomLowerBroadcast() {}@Overridepublic void onReceive(Context context, Intent intent) {if (intent.getAction().equals("SendCustomOrderBroadcast")) {String notice= getResultExtras(true).getString("str_order_broadcast");Toast.makeText(context,notice, Toast.LENGTH_SHORT).show();
// 终止广播继续传播下去abortBroadcast();}}
}
注意 :
有序广播需要声明并使用权限
1.声明使用权限
<!-- 申请使用自定义 有序广播的权限 --><uses-permission > android:name="android.permission.ORDERBROADCAST" />
2.声明权限
<!-- 自定义 有序广播的权限 --><permission>
android:name="android.permission.ORDERBROADCAST"/>
在有序广播中高优先级的广播接收广播,可以修改数据,然后传给低优先级的广播。
3.发送持续广播(已经被弃用)
粘性广播会在Android
系统中一直存在,不过随着 Android
系统的不断更新,此方法逐渐被抛弃,使用方法如下:sendStickyBroadcast(intent);
【腾讯文档】Android 基础知识库
https://docs.qq.com/doc/DSWdKRWh1VnVHYWFP
友情推荐:
Android 开发干货集锦
至此,本篇已结束。转载网络的文章,小编觉得很优秀,欢迎点击阅读原文,支持原创作者,如有侵权,恳请联系小编删除,欢迎您的建议与指正。同时期待您的关注,感谢您的阅读,谢谢!
点击阅读原文,为大佬点赞!
Broadcast 广播使用详解相关推荐
- Numpy的广播机制详解(broadcasting)
Numpy的广播机制详解(broadcasting) 广播(Broadcast)是 numpy 对不同形状(shape)的数组进行数值计算的方式, 对数组的算术运算通常在相应的元素上进行. 如果两个数 ...
- ZAB(Zookeeper Atomic Broadcast)协议详解
一.什么是 Zab协议 ZAB( Zookeeper Atomic Broadcast:Zookeeper原子广播)Zookeeper 通过 ZAB 协议保证分布式事务的最终一致性. [1]ZAB协议 ...
- android 组件(activity,service,content provider,broadcast receiver,intent)详解
Android应用程序由若干个不同类型的组件组合而成,每一个组件具有其特定的安全保护设计方式,它们的安全直接影响到应用程序的安全.Android应用程序组件的主要类型有:活动(Activity),服务 ...
- BroadcastReceiver 广播机制详解
BroadcastReceiver也就是"广播接收者"的意思,顾名思义,它就是用来接收来自系统和应用中的广播. 在Android系统中,广播体现在方方面面,例如当开机完成后系统会产 ...
- 交换机抑制广播命令详解
在企业网络中,广播数据包是一把双刃剑.一方面其是进行正常网络连接所必须的一种数据包,如在自动获得IP地址方案中需要利用广播数据报来寻找可用的DHCP服务器.另一方面其又很容易被病毒或者***所利用,如 ...
- Android 广播机制详解
一.广播的简介 首先,当我们一听到广播这个词时.就可以想到小学是教室的广播.不错Android中的广播机制与我们生活中的广播是有异曲同工之妙的.Android中的发送广播也就像广播室播广播,可以让很多 ...
- Numpy数据分析——花哨索引的简单使用、“广播“规则详解
在对高维数组进行索引时,常会不知从何而起,想提取的部分和实际的效果会出现偏差. 本文将以尽可能容易懂的方式,来揭开Numpy高维数组之间的运算逻辑,并呈现一些简单运用 目录 一.文章用词阐释 1.轴长 ...
- 集线器、交换机以及路由器异同 + 冲突域和广播域详解
转载自:https://blog.csdn.net/gui951753/article/details/79402528 冲突域和广播域 在介绍这三个设备的异同之前,我们首先需要了解冲突域和广播域的概 ...
- Vue中的情侣属性$dispatch和$broadcast详解
$dispatch 和 $broadcast 作为一对情侣 ?属性,在 Vue 1.0 中主要用来实现基于组件树结构的事件流通信 -- 通过向上或向下以冒泡的形式传递事件流,以实现嵌套父子组件的通信. ...
最新文章
- Fedora安装Texlive2013时出现Can't locate Digest/MD5.pm的解决方法
- 爬虫python名词解释_python爬虫
- matlab频分复用,基于MATLAB的频分复用系统的仿真_.doc
- mysql function 参数默认值_MySQL参数log_bin_trust_function_creators介绍
- vue 3.0记录Element UI 表单使用(看了隔壁小孩儿都会用的Element UI 表单组件使用)
- 计算机高一教案,《计算机系统的基本组成》高一信息技术课教案
- Katana的高性能图形分析库
- Unity3D之简单AR游戏
- E - Competitive Seagulls(博弈)
- 基因测序技术发展历史及一、二、三代测序技术原理和应用
- 单片机编程简易计算机的设计,简易计算器设计
- 摄像头焦距与摄像范围的关系表
- Android开机画面定制
- mysqljs基本操作快速上手
- 【OpenCV 笔记】金字塔光流法追踪运动目标
- SLAM轨迹全局误差计算
- 联想Idea Pad Y430 开启VT
- 光纤激光器仿真:(5)类噪声脉冲
- 真·屠龙之术 | 一次SparkSQL性能分析与优化之旅及相关工具小结
- 研发能力保持国际先进水平,亿美软通再获CMMI3认证