preface
Broadcasting plays a very important role in our application. For example, IntentFilter and Intent are often used for broadcast purposes.
Dynamic registration for webcasts is integrated in my Android toolkit project.
directory
- The Activity chapter is a must-know component of Android
- Android must know will be four components — ContentProvider
- The Broadcast Receiver is a must-know component of Android
- Android must know must know four components — Service
Mind mapping
The life cycle
Since there is no direct icon, and Broadcast does not have onCreate or onDestroy, you can only use official documents for verification.
Activity
Static broadcast is no longer supported on Android 8.0
Two kinds of radio
public class NetworkReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION) && App.getInstance() ! =null) { App.getInstance().notifyObservers(isNetConnected(context)); }}}Copy the code
Although they are both broadcast forms, they have to inherit BroadcastReceiver and rewrite the onReceive() method.
Global broadcast
This broadcast can also be used in the app, but the security of this broadcast is questionable.
// Message passing
sendBroadcast(Intent);
Copy the code
- Static broadcast registration
<receiver android:name="com.clericyi.basehelper.network.NetworkReceiver">
<intent-filter>
<action android:name="android.intent.action.BATTERY_LOW"/>
</intent-filter>
</receiver>
Copy the code
- Dynamic broadcast registration
Different from static broadcast, dynamic broadcast needs to be deregistered after registration.
/ / register
networkReceiver = new NetworkReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(networkReceiver, intentFilter);
// log out (if not, a memory leak will occur)
unregisterReceiver(networkReceiver);
Copy the code
In-app broadcast
- Advantages:
- The broadcast is transmitted only within the App itself and will not be leaked to other apps, ensuring data security.
- You can’t receive broadcasts from other apps, which saves all sorts of hassles.
- It is more efficient than global broadcast.
- Method of use
/ / register
networkReceiver = new NetworkReceiver();
localBroadcastManager = LocalBroadcastManager.getInstance(this); // Create the system in singleton mode
localBroadcastManager.registerReceiver(networkReceiver, new IntentFilter("Information that needs to be filtered."));
// Send a message
localBroadcastManager.sendBroadcast(Intent);
/ / logout
localBroadcastManager.unregisterReceiver(networkReceiver);
Copy the code
LocalBroadcastManager source code introduction
Why guideLocalBroadcastManager
The source code?
Binder is not used to communicate with LocalBroadcastManager.
getInstance()
public static LocalBroadcastManager getInstance(@NonNull Context context) {
synchronized (mLock) {
if (mInstance == null) {
mInstance = new LocalBroadcastManager(context.getApplicationContext()); / / 1 - >
}
returnmInstance; }}// The method called directly from comment 1
private LocalBroadcastManager(Context context) {
mAppContext = context;
mHandler = new Handler(context.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_EXEC_PENDING_BROADCASTS:
executePendingBroadcasts();
break;
default:
super.handleMessage(msg); }}}; }Copy the code
So it’s pretty clear here that this is a DCL approach to creating a singleton directly, and in the constructor, we define a Handler.
Let’s make a guess. The nature of our in-app broadcast is actually an asynchronous transmission mechanism based on a Handler. To verify!! We need to understand its sendBroadcast(Intent) method.
sendBroadcast(Intent)
public boolean sendBroadcast(@NonNull Intent intent) {
synchronized (mReceivers) {
// Retrieve the data stored in the incoming Intent
final String action = intent.getAction();
final String type = intent.resolveTypeIfNeeded(
mAppContext.getContentResolver());
final Uri data = intent.getData();
final String scheme = intent.getScheme();
final Set<String> categories = intent.getCategories();
//...
// Get the configured Action
ArrayList<ReceiverRecord> entries = mActions.get(intent.getAction());
if(entries ! =null) {
if (debug) Log.v(TAG, "Action list: " + entries);
ArrayList<ReceiverRecord> receivers = null;
//... Some column operations on variable receivers.
// When there is a receiving object, the data is passed to the Handler.
if(receivers ! =null) {
for (int i=0; i<receivers.size(); i++) {
receivers.get(i).broadcasting = false;
}
mPendingBroadcasts.add(new BroadcastRecord(intent, receivers));
if(! mHandler.hasMessages(MSG_EXEC_PENDING_BROADCASTS)) { mHandler.sendEmptyMessage(MSG_EXEC_PENDING_BROADCASTS); }return true; }}}return false;
}
Copy the code
This has been successfully verified in the code, but LocalBroadcast is ultimately based on the data transfer mechanism of our Handler, which is the biggest difference from application to application broadcast.
conclusion
- What is the difference between dynamic broadcast and static broadcast?
- Static broadcast: Broadcast always exists, consuming large resources and power.
- Dynamic broadcast: The broadcast life cycle is more flexible, less resource consumption. Faster response than static broadcast.
- Broadcasting can also trigger
ANR
The broadcast operation duration cannot exceed 10 seconds. And it doesn’t usually look like it on the airService
andActivity
Be able to useThread
To complete our time-consuming operation. - Global and in-application broadcasts are registered in similar ways, but for different scenarios. If you need Internet, battery, etc., you need global broadcasting. If you only need in-app communication, then you only need in-app broadcasting.
- In-app broadcast (
LocalBroadcast
) the use ofHandler
The message transmission mechanism of Interapplication broadcast or interprocess broadcast (Broadcast
) is used byBinder
The mechanism.