和你一起终身学习,这里是程序员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中注册。

  1. 有序广播静态注册
    接收有序广播的静态注册方法如下:

<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>
  1. 有序广播处理,高优先级广播可以优先处理

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);}}
}
  1. 中优先级的广播后序处理

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);}}
}
  1. 低优先级广播最后处理

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 广播使用详解相关推荐

  1. Numpy的广播机制详解(broadcasting)

    Numpy的广播机制详解(broadcasting) 广播(Broadcast)是 numpy 对不同形状(shape)的数组进行数值计算的方式, 对数组的算术运算通常在相应的元素上进行. 如果两个数 ...

  2. ZAB(Zookeeper Atomic Broadcast)协议详解

    一.什么是 Zab协议 ZAB( Zookeeper Atomic Broadcast:Zookeeper原子广播)Zookeeper 通过 ZAB 协议保证分布式事务的最终一致性. [1]ZAB协议 ...

  3. android 组件(activity,service,content provider,broadcast receiver,intent)详解

    Android应用程序由若干个不同类型的组件组合而成,每一个组件具有其特定的安全保护设计方式,它们的安全直接影响到应用程序的安全.Android应用程序组件的主要类型有:活动(Activity),服务 ...

  4. BroadcastReceiver 广播机制详解

    BroadcastReceiver也就是"广播接收者"的意思,顾名思义,它就是用来接收来自系统和应用中的广播. 在Android系统中,广播体现在方方面面,例如当开机完成后系统会产 ...

  5. 交换机抑制广播命令详解

    在企业网络中,广播数据包是一把双刃剑.一方面其是进行正常网络连接所必须的一种数据包,如在自动获得IP地址方案中需要利用广播数据报来寻找可用的DHCP服务器.另一方面其又很容易被病毒或者***所利用,如 ...

  6. Android 广播机制详解

    一.广播的简介 首先,当我们一听到广播这个词时.就可以想到小学是教室的广播.不错Android中的广播机制与我们生活中的广播是有异曲同工之妙的.Android中的发送广播也就像广播室播广播,可以让很多 ...

  7. Numpy数据分析——花哨索引的简单使用、“广播“规则详解

    在对高维数组进行索引时,常会不知从何而起,想提取的部分和实际的效果会出现偏差. 本文将以尽可能容易懂的方式,来揭开Numpy高维数组之间的运算逻辑,并呈现一些简单运用 目录 一.文章用词阐释 1.轴长 ...

  8. 集线器、交换机以及路由器异同 + 冲突域和广播域详解

    转载自:https://blog.csdn.net/gui951753/article/details/79402528 冲突域和广播域 在介绍这三个设备的异同之前,我们首先需要了解冲突域和广播域的概 ...

  9. Vue中的情侣属性$dispatch和$broadcast详解

    $dispatch 和 $broadcast 作为一对情侣 ?属性,在 Vue 1.0 中主要用来实现基于组件树结构的事件流通信 -- 通过向上或向下以冒泡的形式传递事件流,以实现嵌套父子组件的通信. ...

最新文章

  1. Fedora安装Texlive2013时出现Can't locate Digest/MD5.pm的解决方法
  2. 爬虫python名词解释_python爬虫
  3. matlab频分复用,基于MATLAB的频分复用系统的仿真_.doc
  4. mysql function 参数默认值_MySQL参数log_bin_trust_function_creators介绍
  5. vue 3.0记录Element UI 表单使用(看了隔壁小孩儿都会用的Element UI 表单组件使用)
  6. 计算机高一教案,《计算机系统的基本组成》高一信息技术课教案
  7. Katana的高性能图形分析库
  8. Unity3D之简单AR游戏
  9. E - Competitive Seagulls(博弈)
  10. 基因测序技术发展历史及一、二、三代测序技术原理和应用
  11. 单片机编程简易计算机的设计,简易计算器设计
  12. 摄像头焦距与摄像范围的关系表
  13. Android开机画面定制
  14. mysqljs基本操作快速上手
  15. 【OpenCV 笔记】金字塔光流法追踪运动目标
  16. SLAM轨迹全局误差计算
  17. 联想Idea Pad Y430 开启VT
  18. 光纤激光器仿真:(5)类噪声脉冲
  19. 真·屠龙之术 | 一次SparkSQL性能分析与优化之旅及相关工具小结
  20. 研发能力保持国际先进水平,亿美软通再获CMMI3认证

热门文章

  1. 在 xml 设置的 onClick 属性 为什么有时候点击不起作用呢?
  2. 如何快速学习CADD计算机辅助药物设计
  3. 数据集Cora、Citeseer、DBLP
  4. 大数据技术——MapReduce词频统计
  5. 条件变量(生产者消费者问题)
  6. awstats mysql_GitHub - zw231212/aw2sql: awstats解析结果的解析并将结果数据存入mysql
  7. 微信小程序开店的步骤
  8. 电梯司机是做什么的? (施工升降机)
  9. 如何将简单卷无损数据地变回基本磁盘
  10. python跳转下一页_在selenium python中访问下一页上的元素