Joke Collection Website - Public benefit messages - Use Android local broadcast

Use Android local broadcast

In order to solve the security problem of broadcasting, Android introduced the local broadcasting mechanism, which can only be delivered within the application, and the broadcast receiver can only receive the broadcast from this application.

Static registration cannot receive local broadcasts. We know that static registration is mainly to receive the broadcast when the program is not started, and the program must have been started when we send the local broadcast, so we need dynamic registration to create the receiver.

Here we create a class LocalReceiver that inherits from BroadcastReceiver. OnReceive () handles the broadcast content you receive. Here I use Toast to create a pop-up window to prompt you to receive the message.

Create a button to send a broadcast in the activity_main.xml file.

Firstly, an instance is obtained through the getInstance () method of LocalBroadcastManager, and instances of filter IntentFilter and custom receiver LocalReceiver are created respectively. Add an action:localbroadcast (the name of the received broadcast) to the instance of IntentFilter, and then call the registerReceiver () method of LocalBroadcastManager to register, passing in both the instance of LocalReceiver and the instance of IntentFilter. This completes the creation of the local listener.

Call sendBroadcast () of LocalBroadcastManager to send local broadcast. Run the program and click the send button. We can see that the pop-up window shows "This is at the LocalReceiver", indicating that the local broadcast has been sent and received successfully.

Of course, don't forget to cancel the registration in the end. We can do this by calling the unregisterReceiver () method. At this point, the standard broadcast transmission of Android is completed.

The broadcast sent by 1. can only be transmitted within this program, so don't worry about data leakage.

2. The broadcast of other programs can't be sent to the inside of this program, so don't worry about security holes.

3. Local broadcasting is more effective than system global broadcasting.