[关闭]
@TryLoveCatch 2022-04-22T12:42:09.000000Z 字数 1721 阅读 490

Android知识体系之BroadcastReceiver

Android知识体系


全局广播

注册方式

静态注册

  1. <receiver android:name="com.clericyi.basehelper.network.NetworkReceiver">
  2. <intent-filter>
  3. <action android:name="android.intent.action.BATTERY_LOW"/>
  4. </intent-filter>
  5. </receiver>

动态注册

  1. // 注册
  2. networkReceiver = new NetworkReceiver();
  3. IntentFilter intentFilter = new IntentFilter();
  4. intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
  5. registerReceiver(networkReceiver, intentFilter);
  6. // 注销(如果没有注销,将会发生内存泄漏)
  7. unregisterReceiver(networkReceiver);

小结

发送广播

sendBroadcast()

正常发送广播

sendOrderedBroadcast()

应用内广播

将全局广播设置成局部广播

LocalBroadcastManager

  1. //注册
  2. networkReceiver = new NetworkReceiver();
  3. localBroadcastManager = LocalBroadcastManager.getInstance(this); // --> 以单例模式进行创建
  4. localBroadcastManager.registerReceiver(networkReceiver, new IntentFilter("需要去过滤的信息"));
  5. // 发送消息
  6. localBroadcastManager.sendBroadcast(Intent);
  7. // 注销
  8. localBroadcastManager.unregisterReceiver(networkReceiver);

优点

源码

原理

参考

https://blog.csdn.net/ly0724ok/article/details/117333915
https://www.jianshu.com/p/48010df647ef
https://juejin.cn/post/6844904163613081614
https://juejin.cn/post/6844903972344446984

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注