广播函数列表

说明:帮助刚方便使用广播的工具类,使用简单。

  1. registerBroadcastK :注册广播
  2. unregisterBroadcastK:解除注册
  3. sendBroadcastK :发送广播

一. 介绍

广播,是一个全局的监听器,属于Android四大组件之一. 主要用于监听 / 接收 应用 App 发出的广播消息,并 做出响应.

应用场景有:

  • Android不同组件间的通信(含 :应用内 / 不同应用之间)
  • 多线程通信
  • Android 系统在特定情况下的通信

二. 分类

广播被分为两种不同的类型:“普通广播(Normal broadcasts)”和“有序广播(Ordered broadcasts)”。普通广播是完全异步的,可以在同一时刻(逻辑上)被所有接收者接收到,消息传递的效率比较高,但缺点是:接收者不能将处理结果传递给下一个接收者,并且无法终止广播Intent的传播;然而有序广播是按照接收者声明的优先级别(声明在intent-filter元素的android:priority属性中,数越大优先级别越高,取值范围:-1000到1000。也可以调用IntentFilter对象的setPriority()进行设置),被接收者依次接收广播。如:A的级别高于B,B的级别高于C,那么,广播先传给A,再传给B,最后传给C。A得到广播后,可以往广播里存入数据,当广播传给B时,B可以从广播中得到A存入的数据。

静态注册和动态注册的区别:
944365-8d163ab3ca20de0b.png

1. 静态注册(8.0以后无法使用)

1.无序广播,开发者自身定义 intent的广播(最常用)
  1. 发送方式,显示隐式都可以

    1. public void normalListener(View view) {
    2. // Intent intent = new Intent(this, NormalBroadCaseReceiver.class);
    3. // intent.putExtra("key","broad");
    4. // sendBroadcast(intent);
    5. //隐式启动,如果有多个静态注册的广播action 相同,都会收到
    6. // Intent intent1 = new Intent();
    7. // intent1.setAction("com.kiwilss.broadcase1");
    8. // intent1.putExtra("key", "broad");
    9. // sendBroadcast(intent1);
    10. //8.0以后,想发送成功就要加上 intent1.setPackage(getPackageName());
    11. //原因:谷歌在8.0后为了提高效率,删除了静态注册,防止关闭App后广播还在,
    12. // 造成内存泄漏, 现在静态注册的广播需要指定包名,而动态注册就没有这个问题
    13. Intent intent1 = new Intent();
    14. intent1.setAction("com.kiwilss.broadcase1");
    15. intent1.putExtra("key", "broad");
    16. intent1.setPackage(getPackageName());
    17. sendBroadcast(intent1);
    18. }
  2. 自定义广播
    NormalBroadCaseReceiver

    1. public class NormalBroadCaseReceiver extends BroadcastReceiver {
    2. @SuppressLint("UnsafeProtectedBroadcastReceiver")
    3. @Override
    4. public void onReceive(Context context, Intent intent) {
    5. Log.e(TAG, "onReceive: "+intent.getStringExtra("key") );
    6. }
    7. }
  3. NormalBroadCaseReceiver2

    1. public class NormalBroadCaseReceiver2 extends BroadcastReceiver {
    2. @SuppressLint("UnsafeProtectedBroadcastReceiver")
    3. @Override
    4. public void onReceive(Context context, Intent intent) {
    5. Log.e(TAG, "normal2-------onReceive: "+intent.getStringExtra("key") );
    6. }
    7. }
  4. AndroidManifest.xml里注册

    • 属性说明: ```java

//用于指定此广播接收器将接收的广播类型 //本示例中给出的是用于接收网络状态改变时发出的广播

  1. - 注册示例
  2. ```java
  3. <receiver android:name=".broadcastreceiver.NormalBroadCaseReceiver" tools:ignore="ExportedReceiver">
  4. <intent-filter>
  5. <action android:name="com.kiwilss.broadcase1"/>
  6. <category android:name="android.intent.category.DEFAULT"/>
  7. </intent-filter>
  8. </receiver>
  9. <receiver android:name=".broadcastreceiver.NormalBroadCaseReceiver2" tools:ignore="ExportedReceiver">
  10. <intent-filter>
  11. <action android:name="com.kiwilss.broadcase1"/>
  12. <category android:name="android.intent.category.DEFAULT"/>
  13. </intent-filter>
  14. </receiver>

当此 App首次启动时,系统会自动实例化mBroadcastReceiver类,并注册到系统中。

  1. 测试结果
    04-18 15:52:46.360 12305-12305/com.kiwilss.lxkj.fourassembly E/MMM: onReceive: broad
    04-18 15:52:46.363 12305-12305/com.kiwilss.lxkj.fourassembly E/MMM: normal2———-onReceive: broad

2.有序广播,静态注册
  1. 发送方法和无序广播类似

    1. public void orderlyListener(View view) {
    2. //和无序广播类似
    3. Intent intent1 = new Intent();
    4. intent1.setAction("com.kiwilss.broadcase2");
    5. //intent1.putExtra("key","broad");
    6. intent1.putExtra("key", "orderly");
    7. //null 表示没有权限限制
    8. sendOrderedBroadcast(intent1, null);
    9. }
  2. 自定义广播, 有序广播可以中断传递, 也可以新增传递信息
    OrderlyBroadcastReceiver

    1. public class OrderlyBroadcastReceiver extends BroadcastReceiver {
    2. @Override
    3. public void onReceive(Context context, Intent intent) {
    4. Log.e(TAG, "onReceive: "+intent.getStringExtra("key"));
    5. if (TextUtils.equals("orderly",intent.getStringExtra("key"))) {
    6. //中断传递
    7. abortBroadcast();
    8. }else {
    9. //传递新的信息给下一个广播
    10. Bundle bundle = new Bundle();
    11. bundle.putString("broad","新的信息");
    12. setResultExtras(bundle);
    13. }
    14. }
    15. }
  3. OrderlyBroadcastReceiver2

    1. public class OrderlyBroadcastReceiver2 extends BroadcastReceiver {
    2. @Override
    3. public void onReceive(Context context, Intent intent) {
    4. Log.e(TAG, "onReceive22 : "+intent.getStringExtra("key"));
    5. Bundle bundle = getResultExtras(true);
    6. String broad = bundle.getString("broad");
    7. Log.e(TAG, "onReceive222 : "+ broad );
    8. }
    9. }
  4. 在清单文件中设定优先级

    1. <!--可以设置广播的优先级-->
    2. <receiver android:name=".broadcastreceiver.OrderlyBroadcastReceiver"
    3. >
    4. <intent-filter android:priority="100">
    5. <action android:name="com.kiwilss.broadcase2"/>
    6. <category android:name="android.intent.category.DEFAULT"/>
    7. </intent-filter>
    8. </receiver>
    9. <receiver android:name=".broadcastreceiver.OrderlyBroadcastReceiver2"
    10. >
    11. <intent-filter android:priority="90">
    12. <action android:name="com.kiwilss.broadcase2"/>
    13. <category android:name="android.intent.category.DEFAULT"/>
    14. </intent-filter>
    15. </receiver>

4.测试结果

  1. 中断传播结果:
  2. 04-18 16:23:30.380 15795-15795/com.kiwilss.lxkj.fourassembly E/MMM: onReceive: orderly

新增信息结果:

04-18 16:30:35.026 16342-16342/com.kiwilss.lxkj.fourassembly E/MMM: onReceive: broad
04-18 16:30:35.074 16342-16342/com.kiwilss.lxkj.fourassembly E/MMM: onReceive22 : broad
04-18 16:30:35.074 16342-16342/com.kiwilss.lxkj.fourassembly E/MMM: onReceive222 : 新的信息

3.动态注册
  1. 发送方式

    1. /**普通广播,动态注册
    2. * @param view
    3. */
    4. public void normalDynamicListener(View view) {
    5. //动态注册广播发送消息
    6. Intent intent = new Intent("com.kiwilss.normaldynamic");
    7. intent.putExtra("key","普通广播动态注册");
    8. sendBroadcast(intent);
    9. }
  2. 注册和解除注册 ```java @Override protected void onResume() {

    1. super.onResume();
    2. //普通广播注册
    3. if (mBroadcastReceiver == null){
    4. mBroadcastReceiver = new LocalBroadcastReceiver();
    5. IntentFilter intentFilter = new IntentFilter("com.kiwilss.normaldynamic");
    6. registerReceiver(mBroadcastReceiver,intentFilter);
    7. }

    }

@Override protected void onPause() { super.onPause(); //普通广播解除注册 if (mBroadcastReceiver != null) { unregisterReceiver(mBroadcastReceiver); } }

  1. - 动态广播最好在`Activity` `onResume()`注册、`onPause()`注销。
  2. - 原因:
  3. 1. 对于动态广播,有注册就必然得有注销,否则会导致**内存泄露**
  4. 1. 重复注册、重复注销也不允许
  5. 3. 自定义广播
  6. ```java
  7. class LocalBroadcastReceiver extends BroadcastReceiver {
  8. @Override
  9. public void onReceive(Context context, Intent intent) {
  10. Log.e("MMM", "onReceive: " + intent.getStringExtra("key"));
  11. }
  12. }
  1. 测试结果
    04-18 16:52:14.730 17989-17989/com.kiwilss.lxkj.fourassembly E/MMM: onReceive: 普通广播动态注册

4. 本地广播 App应用内广播(Local Broadcast)
  1. Android中的广播可以跨App直接通信(exported对于有intent-filter情况下默认值为true)

可能出现的问题:

  • 其他App针对性发出与当前App intent-filter相匹配的广播,由此导致当前App不断接收广播并处理;
  • 其他App注册与当前App一致的intent-filter用于接收广播,获取广播具体信息;
    即会出现安全性 & 效率性的问题。
  • 解决方案
    使用App应用内广播(Local Broadcast)
    1. App应用内广播可理解为一种局部广播,广播的发送者和接收者都同属于一个App。
    2. 相比于全局广播(普通广播),App应用内广播优势体现在:安全性高 & 效率高
  1. 具体使用
    发送方法: ```java /**
    • 对于LocalBroadcastManager方式发送的应用内广播,
    • 只能通过LocalBroadcastManager动态注册,不能静态注册 *
    • @param view */ public void appListener(View view) { //注册应用内广播接收器 //步骤1:实例化BroadcastReceiver子类 & IntentFilter mBroadcastReceiver mBroadcastReceiver = new LocalBroadcastReceiver(); IntentFilter intentFilter = new IntentFilter(); //步骤2:实例化LocalBroadcastManager的实例 localBroadcastManager = LocalBroadcastManager.getInstance(this); //步骤3:设置接收广播的类型 intentFilter.addAction(“com.kiwilss.local”); //4,注册 localBroadcastManager.registerReceiver(mBroadcastReceiver, intentFilter);
  1. //发送应用内广播测试
  2. Intent intent = new Intent("com.kiwilss.local");
  3. intent.putExtra("key","本地广播");
  4. localBroadcastManager.sendBroadcast(intent);
  5. }
  6. @Override
  7. protected void onDestroy() {
  8. super.onDestroy();
  9. //取消注册本地广播
  10. if (mBroadcastReceiver != null)
  11. localBroadcastManager.unregisterReceiver(mBroadcastReceiver);
  12. //取消网络监听注册
  13. if (netBroadcastReceiver != null)
  14. unregisterReceiver(netBroadcastReceiver);
  15. }
  1. 3. 自定义广播
  2. ```java
  3. class LocalBroadcastReceiver extends BroadcastReceiver {
  4. @Override
  5. public void onReceive(Context context, Intent intent) {
  6. Log.e("MMM", "onReceive: " + intent.getStringExtra("key"));
  7. }
  8. }
  1. 测试结果
    04-18 16:57:28.905 17989-17989/com.kiwilss.lxkj.fourassembly E/MMM: onReceive: 本地广播

5.系统广播(System Broadcast)
  1. 介绍
  • Android中内置了多个系统广播:只要涉及到手机的基本操作(如开机、网络状态变化、拍照等等),都会发出相应的广播
  • 每个广播都有特定的Intent - Filter(包括具体的action),Android系统广播action如下: | 系统操作 | action | | —- | —- | | 监听网络变化 | android.net.conn.CONNECTIVITY_CHANGE | | 关闭或打开飞行模式 | Intent.ACTION_AIRPLANE_MODE_CHANGED | | 充电时或电量发生变化 | Intent.ACTION_BATTERY_CHANGED | | 电池电量低 | Intent.ACTION_BATTERY_LOW | | 电池电量充足(即从电量低变化到饱满时会发出广播 | Intent.ACTION_BATTERY_OKAY | | 系统启动完成后(仅广播一次) | Intent.ACTION_BOOT_COMPLETED | | 按下照相时的拍照按键(硬件按键)时 | Intent.ACTION_CAMERA_BUTTON | | 屏幕锁屏 | Intent.ACTION_CLOSE_SYSTEM_DIALOGS | | 设备当前设置被改变时(界面语言、设备方向等) | Intent.ACTION_CONFIGURATION_CHANGED | | 插入耳机时 | Intent.ACTION_HEADSET_PLUG | | 未正确移除SD卡但已取出来时(正确移除方法:设置—SD卡和设备内存—卸载SD卡) | Intent.ACTION_MEDIA_BAD_REMOVAL | | 插入外部储存装置(如SD卡) | Intent.ACTION_MEDIA_CHECKING | | 成功安装APK | Intent.ACTION_PACKAGE_ADDED | | 成功删除APK | Intent.ACTION_PACKAGE_REMOVED | | 重启设备 | Intent.ACTION_REBOOT | | 屏幕被关闭 | Intent.ACTION_SCREEN_OFF | | 屏幕被打开 | Intent.ACTION_SCREEN_ON | | 关闭系统时 | Intent.ACTION_SHUTDOWN | | 重启设备 | Intent.ACTION_REBOOT |

  • 注:当使用系统广播时,只需要在注册广播接收者时定义相关的action即可,并不需要手动发送广播,当系统有相关操作时会自动进行系统广播

  1. 使用示例, 监听手机网络状态

    1. 方法 ```java /**系统广播,示例监听网络
    • @param view */ NetBroadcastReceiver netBroadcastReceiver; public void appDynamicListener(View view) { netBroadcastReceiver = new NetBroadcastReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(“android.net.conn.CONNECTIVITY_CHANGE”); registerReceiver(netBroadcastReceiver,intentFilter); //ondestory中取消注册 } ```
    1. 自定义广播

      1. class NetBroadcastReceiver extends BroadcastReceiver{
      2. @Override
      3. public void onReceive(Context context, Intent intent) {
      4. Log.e("MMM", "onReceive: 网络有变化" );
      5. //连接或是关闭网络时可以监控
      6. }
      7. }
    2. 测试, 关闭打开手机网络
      04-18 17:02:03.220 17989-17989/com.kiwilss.lxkj.fourassembly E/MMM: onReceive: 网络有变化
      04-18 17:02:06.834 17989-17989/com.kiwilss.lxkj.fourassembly E/MMM: onReceive: 网络有变化
      04-18 17:02:13.506 17989-17989/com.kiwilss.lxkj.fourassembly E/MMM: onReceive: 网络有变化

      三.动态注册帮助类

      鉴于各种限制,尽量使用动态注册,所以写了一个帮助类,方便快速注册和解除注册广播。比较简单,代码如下: ```kotlin object BroadcastKtx { /**

      • 注册广播 *
      • @param context
      • @param broadcastReceiver
      • @param action */ fun registerBroadcast( context: Context?, broadcastReceiver: BroadcastReceiver?, vararg action: String? ) { if (context == null || broadcastReceiver == null) return val intentFilter = IntentFilter() for (element in action) {
        1. intentFilter.addAction(element)
        } context.registerReceiver(broadcastReceiver, intentFilter) }

      /**

      • 解除注册广播,广播要和注册时是同一个 *
      • @param context
      • @param broadcastReceiver */ fun unregisterBroadcast(context: Context?, broadcastReceiver: BroadcastReceiver?) { if (context == null || broadcastReceiver == null) return context.unregisterReceiver(broadcastReceiver) }

      /* 发送广播

      • @param context
      • @param action
      • @param pair / fun sendBroadcast(context: Context?, action: String?, vararg pair: Pair) { if (context == null || action.isNullOrEmpty()) return context.sendBroadcast(context.createBroadcastIntent(action, pair)) }

}

/**

  • 注册广播 *
  • @param broadcastReceiver
  • @param action / fun Context?.registerBroadcast( broadcastReceiver: BroadcastReceiver?, vararg action: String? ) = BroadcastKtx.registerBroadcast(this, broadcastReceiver, action)

/**

  • 解除注册广播,广播要和注册时是同一个 *
  • @param broadcastReceiver */ fun Context?.unregisterBroadcast(broadcastReceiver: BroadcastReceiver?) = BroadcastKtx.unregisterBroadcast(this, broadcastReceiver)

/**

  • 注册广播 *
  • @param broadcastReceiver
  • @param action / fun Fragment?.registerBroadcast( broadcastReceiver: BroadcastReceiver?, vararg action: String? ) = BroadcastKtx.registerBroadcast(this?.context, broadcastReceiver, action)

/**

  • 解除注册广播,广播要和注册时是同一个 *
  • @param broadcastReceiver */ fun Fragment?.unregisterBroadcast(broadcastReceiver: BroadcastReceiver?) = BroadcastKtx.unregisterBroadcast(this?.context, broadcastReceiver)

/* 发送广播

  • @param action
  • @param pair / fun Context?.sendBroadcast(action: String?, vararg pair: Pair) = BroadcastKtx.sendBroadcast(this, action, pair)

/* 发送广播

  • @param action
  • @param pair / fun Fragment?.sendBroadcast(action: String?, vararg pair: Pair) = BroadcastKtx.sendBroadcast(this?.context, action, pair) 使用很简单,在 Activity/Fragment 中直接使用,示例 demo如下:kotlin class BroadcastActivity: AppCompatActivity(R.layout.activity_broadcast) { override fun onCreate(savedInstanceState: Bundle?) {
    1. super.onCreate(savedInstanceState)
  1. btnSend.setOnClickListener {
  2. //发送广播信息
  3. sendBroadcast(createIntentBroadcast(action1,"broad" to "test broadcast"))
  4. //或者下面这样
  5. sendBroadcast(action1,"broad" to "test broadcast")
  6. }
  7. }
  8. //初始化广播
  9. val mTestBroadcast by lazy { TestBroadcast() }
  10. val action1 = "com.kiwilss.broadcase1"
  11. override fun onResume() {
  12. super.onResume()
  13. //注册,可以注册很多个 action
  14. registerBroadcast(mTestBroadcast,action1)
  15. }
  16. override fun onPause() {
  17. super.onPause()
  18. unregisterBroadcast(mTestBroadcast)
  19. }

}

class TestBroadcast: BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { val action = intent?.action Log.e(“MMM”, “onReceive: $action —- ${intent?.getStringExtra(“broad”)}”); } } ```

四、参考

Android四大组件:BroadcastReceiver史上最全面解析
Android 四大组件
demo