前言
本地广播只能在应用程序内部进行传递,并且只能通过动态注册.这种本地广播的好处是不会将一些隐蔽信息被全局广播出去.
全局静态与动态广播
在8.0版本以后,全局广播权限收紧,其实已经没有什么静态与动态的区别了.... 虽然还支持静态这种写法,但是实际上还是需要动态注册广播。下面就来讲解8.0之后的全局广播接收与发送
接收
class KeyReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { Log.e("zh", "接收到广播 : = ${intent.action} ", ) when (intent.action){ "com.zh.dev.KeyReceiver.enable" -> RemoteControlService.sIsEnableRemoteControlFunction = true "com.zh.dev.KeyReceiver.disable" -> RemoteControlService.sIsEnableRemoteControlFunction = false } } }
AndroidManifest.xml
<application> <receiver android:name=".KeyReceiver" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="com.zh.dev.KeyReceiver.enable"/> <action android:name="com.zh.dev.KeyReceiver.disable"/> </intent-filter> </receiver> </application>
千万记得要动态注册
registerReceiver(KeyReceiver(), IntentFilter().apply { addAction("com.zh.dev.KeyReceiver.enable") addAction("com.zh.dev.KeyReceiver.disable") })
发送
val disableIntent = Intent("com.lwlx.dev.LwlxKeyReceiver.disable") //现在必须添加component,以约束发送广播的范围。不添加会导致广播无法成功发送,下面第一个参数是目标apk包名,第二个参数是目标广播类 disableIntent.component = ComponentName("com.zh.dev", "com.zh.remotecontrol.KeyReceiver") sendBroadcast(disableIntent)
本地广播
这种广播只作用app内部
创建广播接受类,继承BroadcastReceiver
public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (TextUtils.equals(intent.getAction(), DEMO_ACTION)){ Toast.makeText(context, "触发本地广播", Toast.LENGTH_SHORT).show(); } } }
注册广播,请注意,注册本地广播需要使用LocalBroadcastManager进行注册,这点与静态广播不通.
private CloseDialogReceiver mCloseDialogReceiver; private void registerReceiver(){ mCloseDialogReceiver = new CloseDialogReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(DEMO_ACTION); LocalBroadcastManager.getInstance(this).registerReceiver(mCloseDialogReceiver, intentFilter); }
发送广播,发送也需要使用LocalBroadcastManager发送
public void send(){ Intent dismissDialog = new Intent(DEMO_ACTION); LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this); localBroadcastManager.sendBroadcast(dismissDialog); }
注销广播
LocalBroadcastManager.getInstance(this).unregisterReceiver(mCloseDialogReceiver);
本文来自博客园,作者:观心静 ,转载请注明原文链接:https://www.cnblogs.com/guanxinjing/p/14781010.html
本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。