[TOC]

概述

比如在当前 Activity 下动态注册一个广播,我们会这样做:

1
this.registerReceiver(receiver, filter)

这样的话,这个 receiver 组件是完全公开的,不仅仅我们的应用可以向它发送数据,外部应用也可以指定相应的 action 来向它发送恶意数据。

为了提高安全性,则需要对其进行权限限制,有两种措施:

方案一

1
registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)

该方法还是允许接收外部的广播,但添加了权限来进行限制。

在动态注册中的代码

1
2
3
4
5
6
BroadcastReceiver receiver = new MyBroadcastReceiver();
Handler handler = new MyHandler();
IntentFilter filter = new IntentFilter();
filter.addAction("me.lynch.action.test");
String permission = "me.lynch.permission.test";
context.register(receiver, filter, permission, handler);

如果使用的是静态注册,那就是这样:

1
2
3
4
5
6
7
8
9
<permission android:name = "me.lynch.permission.test"/>  

...

<receiver android:name="MyBroadcastReceiver" android:permission="me.lynch.permission.test">
<intent-filter>
<action android:name="me.lynch.action.test" />
</intent-filter>
</receiver>

这样的话,只有拥有了 “me.lynch.permission.test” 的权限的应用才能给该 BroadcastReceiver 发广播。

1
2
3
4
5
<uses-permission android:name="me.lynch.permission.test" />

Intent intent = new Intent();
intent.setAction("me.lynch.action.test");
sendBrocast(intent, "me.lynch.permission.test");

方案二

LocalBroadcastManager

这是一个工具类,可以用来限制 BroadcastReceiver 的使用,只能应用内发送和接收广播

注册广播

1
2
3
4
5
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(context);
BroadcastReceiver receiver = new MyBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("me.lynch.action.test");
manager.register(receiver, filter);

发送广播

1
2
3
Intent intent = new Intent();
intent.setAction("me.lynch.action.test");
manager.sendBrocast(intent);