In the Android system, broadcastreceiver is designed globally to facilitate communications between applications and systems, applications, and applications, therefore, for a single application, broadcastreceiver has security problems. The corresponding problems and solutions are as follows:
1. When an application sends a broadcast, the system matches the intent sent with the intentfilter of all registered broadcastreceiver in the system. If the match succeeds, the corresponding onreceive function is executed. You can use an interface similar to sendbroadcast (intent, string) to specify the permission required by the receiver when sending a broadcast. Or you can use intent. setpackage to set the broadcast to only be valid for a program.
2. When an application registers a broadcast, even if intentfilter is set, it still receives the broadcast from other applications for matching and judgment. For Dynamic Registration broadcast, you can use a broadcast like registerreceiver (broadcastreceiver, intentfilter, String, android. OS. handler) interface specifies the permission that the sender must possess. For static registration broadcasts, you can use the Android: exported = "false" attribute to indicate that the receiver is unavailable to external applications, that is, broadcast from outside is not accepted.
The above two problems can be solved through localbroadcastmanager:
Android V4 compatibility package provides android. support. v4.content. the localbroadcastmanager tool class helps you to send and register local broadcasts in your own processes. Using it has the following advantages over sending system global broadcasts through sendbroadcast (intent.
1. Because broadcast data is transmitted in this application, you do not have to worry about the leakage of private data.
2. Do not worry about other applications forging broadcasts, which may cause security risks.
3 It is more efficient than sending global broadcasts in the system.
Its usage is similar to that of the normal registration broadcast:
Localbroadcastmanager mlocalbroadcastmanager; broadcastreceiver mreceiver; intentfilter filter = new intentfilter (); filter. addaction ("test "); mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals("test")) { //Do Something } } };
Mlocalbroadcastmanager. registerreceiver (mreceiver, filter );
Of course, like normal broadcast, it should also be unregistered in the corresponding lifecycle:
@Overrideprotected void onDestroy() { super.onDestroy(); mLocalBroadcastManager.unregisterReceiver(mReceiver);}