Joke Collection Website - Public benefit messages - Use Android local broadcast
Use Android local broadcast
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.
- Related articles
- Three people sent each other a WeChat. How many messages did they send?
- How to inquire about Changan Financial Car Loan?
- Is it reliable for Nanjing Bank Meng Xin to enjoy loan repayment? Is the actual interest high? How many installments can I repay separately?
- Why does Xiaomi 4 show insufficient memory?
- A cold greeting is brief to customers.
- Defendant Lianshui PICC Property Insurance Company.
- What is the spirit of Shenzhen Special Economic Zone?
- Everbright credit card has been approved for several days, and you haven't sent me a message. What happened?
- Can I send a letter by SMS after taking a photo?
- Chunequinox SMS interception