1、概念

广播分为发广播和广播接收者,类似于广播发射器和收音机。
在整个Android开发中,主要研究的就是发广播和接收广播。

2、广播的分类

从发广播的角度来说:分为系统广播和第三方广播
从接收的顺序上来说:分为有序广播和无需广播。

常见的系统广播如:系统开机完成的广播,电量改变的广播,usb是否连接的广播,wifi状态改变的广播等等

3、动态注册广播(监听电量变化)

package com.example.broadcastreceiverexample.batteryChange.BatteryChangeActivity;import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;import com.example.broadcastreceiverexample.R;/*** 动态注册:* 节省资源,不用一直监听* 跟随着Activity的生命周期走*/
public class BatteryChangeActivity extends AppCompatActivity {private static final String TAG = "BatteryChangeActivity";private BatterLevelReceiver mBatterLevelReceiver;@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_battery_change);registerBroadcastReceiver();}/*** 第二步:注册一个BroadcastReceicer*/private void registerBroadcastReceiver() {//创建一个意图过滤器IntentFilter intentFilter = new IntentFilter();//设置频道intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);//设置成全局变量,方便在此应用销毁的时候取消注册的广播mBatterLevelReceiver = new BatterLevelReceiver();//注册registerReceiver(mBatterLevelReceiver,intentFilter);}/*** 第一步:创建一个内部类,即创建一个广播接收者,继承BroadcastReceiver*/private class BatterLevelReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();Log.d(TAG,"收到电量变化的广播---action is "+action);Log.d(TAG,"当前的电量为:"+ intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0));Log.d(TAG,"当前最大的电量为:"+ intent.getIntExtra(BatteryManager.EXTRA_SCALE,0));}}@Overrideprotected void onDestroy() {super.onDestroy();//在销毁此Activity时,取消广播注册,否则会造成内存泄露if (mBatterLevelReceiver != null) {unregisterReceiver(mBatterLevelReceiver);Log.d(TAG, "onDestroy: 广播注销完成");}}
}

在如上的demo中,涉及到以下几个知识点:

1、android.content.intent中的ACTION_BATTERY_CHANGED(系统广播)/*** Broadcast Action:  This is a <em>sticky broadcast</em> containing the* charging state, level, and other information about the battery.* See {@link android.os.BatteryManager} for documentation on the* contents of the Intent.** <p class="note">* You <em>cannot</em> receive this through components declared* in manifests, only by explicitly registering for it with* {@link Context#registerReceiver(BroadcastReceiver, IntentFilter)* Context.registerReceiver()}.  See {@link #ACTION_BATTERY_LOW},* {@link #ACTION_BATTERY_OKAY}, {@link #ACTION_POWER_CONNECTED},* and {@link #ACTION_POWER_DISCONNECTED} for distinct battery-related* broadcasts that are sent and can be received through manifest* receivers.** <p class="note">This is a protected intent that can only be sent* by the system.*/@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)public static final String ACTION_BATTERY_CHANGED = "android.intent.action.BATTERY_CHANGED";2、android.os.BatteryManager中的EXTRA_LEVEL(当前电量)和EXTRA_SCALE (最大电量)/*** Extra for {@link android.content.Intent#ACTION_BATTERY_CHANGED}:* integer field containing the current battery level, from 0 to* {@link #EXTRA_SCALE}.*/public static final String EXTRA_LEVEL = "level";/*** Extra for {@link android.content.Intent#ACTION_BATTERY_CHANGED}:* integer containing the maximum battery level.*/public static final String EXTRA_SCALE = "scale";

4、静态注册广播(监听开机完成)

package com.example.broadcastreceiverexample.batteryChange.BatteryChangeActivity;import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;/*** 第一步创建一个类,并继承BroadcastReceiver* 静态注册比较耗资源,一直处于监听的状态。静态注册的广播优先级高于动态注册的广播*/
public class BootCompleteReceiver extends BroadcastReceiver {private static final String TAG = "BootCompleteReceiver";@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();Log.d(TAG, "action is "+action);Log.d(TAG, "onReceive: 开机完成...");try {//添加一个线程,在开机后更明显的显示ToastThread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}Toast.makeText(context,"开机完成,接收到了广播",Toast.LENGTH_LONG).show();}
}
    <!--添加权限,之所以添加权限,与BOOT_COMPLETED有关--><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/><!--静态注册--><receiver android:name=".batteryChange.BatteryChangeActivity.BootCompleteReceiver"><!--第二步:添加action--><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED"></action></intent-filter></receiver>
在源码中这样写到,需要添加RECEIVE_BOOT_COMPLETED权限才能使用/*** Broadcast Action: This is broadcast once, after the user has finished* booting. It can be used to perform application-specific initialization,* such as installing alarms. You must hold the* {@link android.Manifest.permission#RECEIVE_BOOT_COMPLETED} permission in* order to receive this broadcast.* <p>* This broadcast is sent at boot by all devices (both with and without* direct boot support). Upon receipt of this broadcast, the user is* unlocked and both device-protected and credential-protected storage can* accessed safely.* <p>* If you need to run while the user is still locked (before they've entered* their lock pattern or PIN for the first time), you can listen for the* {@link #ACTION_LOCKED_BOOT_COMPLETED} broadcast.* <p class="note">* This is a protected intent that can only be sent by the system.*/@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)@BroadcastBehavior(includeBackground = true)public static final String ACTION_BOOT_COMPLETED = "android.intent.action.BOOT_COMPLETED";

5、注意事项

在Android 8.0之后,不推荐使用静态注册的方式去注册广播。官方说明如下:

As part of the Android 8.0 (API level 26) Background Execution Limits, apps that target the API level 26 or higher can no longer register broadcast receivers for implicit broadcasts in their manifest. However, several broadcasts are currently exempted from these limitations. Apps can continue to register listeners for the following broadcasts, no matter what API level the apps target.

仅为学习过程中的记录,方便自己以后查阅,也希望能帮助到每一位查阅者。其它广播详情均可参考Android Developer中的详细介绍。
参考文献地址:https://developer.android.google.cn/training/permissions/requesting#principles

Android--BroadcastReceiver相关推荐

  1. Android BroadcastReceiver中播放提示语音有时失效问题

    Android BroadcastReceiver 千万不要做耗时的操作,如果有耗时的操作,请让OnReceive 中调用service. @Override public void onReceiv ...

  2. Android BroadcastReceiver示例教程

    Today we'll discuss and implement Android BroadcastReceiver that is a very important component of An ...

  3. Android BroadcastReceiver总结

    #BroadcastReceiver综述 广播接收器,顾名思义,用来接收广播的. 一个广播关联两个角色,广播发送方.广播接收方,BroadcastReceiver是接收方角色. 广播发送方可以是应用内 ...

  4. Android BroadcastReceiver广播接收android:priority优先级超过1000,达到2147483647时,广播优先级是否生效

    Android BroadcastReceiver广播接收android:priority优先级超过1000,达到2147483647时,广播优先级是否生效 本文作者使用priority=" ...

  5. android系统休眠发广播,Android - BroadcastReceiver

    BroadcastReceiver BroadcastReceiver,广播接收者,用来接收系统和应用的广播,并做出相应的处理,如电量过低时提示用户充电等: BroadcastReceiver 是 A ...

  6. android广播过滤器.*,android – BroadcastReceiver与多个过滤器或多个BroadcastReceivers?...

    我有一个Android Activity需要捕获两个不同的广播.我目前的方法是在活动中有一个单一的BroadcastReceiver,并抓住它的广播: public class MyActivity ...

  7. 【转】Android BroadcastReceiver介绍

    本文主要介绍BroadcastReceiver的概念.使用.生命周期.安全性.分类.特殊的BroadcastReceiver(本地.粘性.有序.粘性有序广播). 示例代码见BroadcastRecei ...

  8. Android BroadcastReceiver广播详解

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

  9. Android BroadcastReceiver,广播与进程通讯,APK安装广播,获取已安装列表

    1.创建广播接收器: /*** 作者:created by meixi* 邮箱:13164716840@163.com* 日期:2018/11/1 09*/ public class MyBroadc ...

  10. Android BroadcastReceiver应用

    1. 创建Receiver,两种方式,动态和静态: (1)静态注册: 首先自定义个Receiver, public class MyReceiver extends BroadcastReceiver ...

最新文章

  1. git submodule获取子模块
  2. c语言不用switch做计算器,超级新手,用switch写了个计算器程序,求指导
  3. Python与Java之间的相互调用——Jython
  4. SAP 电商云 Accelerator 和 Spartacus UI 的工作机制差异
  5. 电脑技巧:电脑几种常见的系统故障解答
  6. cf1511B. GCD Length
  7. 文件服务器监控用户修改信息,文件服务器监控日志软件
  8. 前端多行文本溢出问题解决方案
  9. idea如何打开pom引用依赖_IDEA使用Maven管理项目包,缺少pom文件中引入的依赖包...
  10. 活动报名 | 苏州工业园区领军人才项目申报宣讲对接会
  11. C++交换两个数组的前n个字节
  12. WebSphere 管理员界面 修改配置之后,没有反应的原因,需要按下[保存]link
  13. Kubernetes Job Controller源码分析
  14. 教你定时爬取微博热搜榜并做动态数据展示,让你不错过任何一个吃瓜热点
  15. 华为光猫上线流程、注册失败、常见语音故障处理
  16. 发出警报声的c语言程序,1、编写一个函数能够发出警报声并打印HelloWorld!;
  17. 如何更改win7开机启动画面
  18. css translate 坐标,CSS3 位移转换 translate3d()translatez()应用实例
  19. 爬取豆瓣排名前100的电影
  20. Win10 中查看笔记本电脑电池信息

热门文章

  1. 基于STC8G2K64S4单片机控制小车循迹(直流电机和步进电机)
  2. 节省你学习时间的百余个谷歌小技巧
  3. Java初学者作业——编写Java程序, 实现根据用户购买商品总金额, 计算实际支付的金额及所获得的购物券金额。
  4. 基于参考辐射源/定标的校正算法
  5. excel表格怎么调整行高和列宽_如何在Excel中竖向批量插入图片,这个简单方法你知道吗...
  6. 0基础入行学习软件测试有哪些要求?往往只有这3点
  7. OSI 七层网络结构
  8. 【该文章已被封禁】区块链钱包APP逆向分析及实现
  9. openFoam+paraview 显示网格cellID
  10. python | 自动化exe程序