概述
比如在当前 Activity 下动态注册一个广播,我们会这样做
this.registerReceiver(receiver, filter)
这样的话,这个 receiver 组件是完全公开的,不仅仅我们的应用可以向它发送数据,外部应用也可以指定相应的 action 来向它发送恶意数据
为了提高安全性,则需要对其进行权限限制,有两种措施
方案一
registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)
该方法还是允许接收外部的广播,但添加了权限来进行限制
在动态注册中的代码
BroadcastReceiver receiver = new CBroadcastReceiver();
Handler handler = new CHandler();
IntentFilter filter = new IntentFilter();
filter.addAction("com.mirror.js");
String permission = "com.mirror.js.permission";
context.register(receiver, filter, permission, handler);
如果使用的是静态注册,那就是这样
<permission android:name = "com.mirror.js.permission"/>
...
<receiver android:name="CBroadcastReceiver" android:permission="com.mirror.js.permission">
<intent-filter>
<action android:name="com.mirror.js" />
</intent-filter>
</receiver>
这样的话,只有拥有了 “com.mirror.js.permission” 的权限的应用才能给该 BroadcastReceiver 发广播
Intent intent = new Intent();
intent.setAction("com.mirror.js");
sendBrocast(intent, "com.mirror.js.permission");
方案二
LocalBroadcastManager
这是一个工具类,可以用来限制 BroadcastReceiver 的使用,只能应用内发送和接收广播
注册广播
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(context);
BroadcastReceiver receiver = new MyBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.mirror.js");
manager.register(receiver, filter);
发送广播
Intent intent = new Intent();
intent.setAction("com.mirror.js");
manager.sendBrocast(intent);