Android programming-detailed explanation of LocalBroadcastManager source code

Source: Internet
Author: User

LocalBroadcastManager is a class in the V4 package. It is mainly responsible for registering and sending internal broadcasts. That is to say, it only applies to registering and sending broadcasts in the Code. It is not applicable to broadcast receiving registered in AndroidManifest.

The official English explanation is as follows:

Helper to register for and send broadcasts of Intents to local objects within your process. This is has a number of advantages over sending global broadcasts with sendBroadcast (Intent ):

You know that the data you are broadcasting won't leave your app, so don't need to worry about leaking private data.
It is not possible for other applications to send these broadcasts to your app, so you don't need to worry about having security holes they can exploit.
It is more efficient than sending a global broadcast through the system.


Next, let's take a look at the global variables:

private final Context mAppContext;private final HashMap
 
  > mReceivers = new HashMap();private final HashMap
  
   > mActions = new HashMap();private final ArrayList
   
     mPendingBroadcasts = new ArrayList();static final int MSG_EXEC_PENDING_BROADCASTS = 1;private final Handler mHandler;private static final Object mLock = new Object();private static LocalBroadcastManager mInstance;
   
  
 

MAppContext: ApplicationContext, so you don't have to worry about memory leakage.

MReceivers: record the array of the registered BroadcastReceiver and its IntentFilter. Here we will discuss why it is an array.

MActions: record the BroadcastReceiver array corresponding to the action in IntentFilter. Although the ReceiverRecord type is written here, it is actually an internal class that stores BroadcastReceiver and its corresponding IntentFilter.

MPendingBroadcasts: when sending a broadcast, the corresponding BroadcastReceiver is found based on the Intent action. Remember? Action can correspond to multiple BroadcastReceiver, so here is an array.

MHandler: Let's do one thing and send a broadcast.

MLock: Synchronous lock.

MInstance: your own instance object. You may have guessed it with experience. That's right. LocalBroadcastManager is a singleton.


Let's take a look at its construction method. The standard Singleton method is as follows:

public static LocalBroadcastManager getInstance(Context context) {synchronized (mLock) {if (mInstance == null) {mInstance = new LocalBroadcastManager(context.getApplicationContext());}return mInstance;}}private LocalBroadcastManager(Context context) {this.mAppContext = context;this.mHandler = new Handler(context.getMainLooper()) {public void handleMessage(Message msg) {switch (msg.what) {case MSG_EXEC_PENDING_BROADCASTS:LocalBroadcastManager.this.executePendingBroadcasts();break;default:super.handleMessage(msg);}}};}

The mAppContext mentioned above is the evidence of ApplicationContext: mInstance = new LocalBroadcastManager (context. getApplicationContext ());

The mHandler is created during the constructor, and an internal task is done to send the broadcast: executePendingBroadcasts.


Next, let's take a look at how to register a broadcast receiver:

public void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {synchronized (this.mReceivers) {ReceiverRecord entry = new ReceiverRecord(filter, receiver);ArrayList filters = (ArrayList) this.mReceivers.get(receiver);if (filters == null) {filters = new ArrayList(1);this.mReceivers.put(receiver, filters);}filters.add(filter);for (int i = 0; i < filter.countActions(); i++) {String action = filter.getAction(i);ArrayList entries = (ArrayList) this.mActions.get(action);if (entries == null) {entries = new ArrayList(1);this.mActions.put(action, entries);}entries.add(entry);}}}

It is to establish a one-to-many correspondence between BroadcastReceiver and IntentFilter. You can find the corresponding IntentFilter through BroadcastReceiver, or find the corresponding BroadcastReceiver through the action in IntentFilter. Here, we also need to explain why the stored IntentFilter in the mReceivers mentioned above is in the array format. We know that IntentFilter can store multiple actions, which is why it is initialized into an array of 1 length. The meaning of the array here is actually very simple, that is, multiple intentfilters can be imported. Although multiple intentfilters can be imported, if the action in the filter is of the same name, it is still processed in the same way. The code below shows that the action is saved as a key.


If you have registered, you must cancel the registration:

public void unregisterReceiver(BroadcastReceiver receiver) {synchronized (this.mReceivers) {ArrayList filters = (ArrayList) this.mReceivers.remove(receiver);if (filters == null) {return;}for (int i = 0; i < filters.size(); i++) {IntentFilter filter = (IntentFilter) filters.get(i);for (int j = 0; j < filter.countActions(); j++) {String action = filter.getAction(j);ArrayList receivers = (ArrayList) this.mActions.get(action);if (receivers != null) {for (int k = 0; k < receivers.size(); k++) {if (((ReceiverRecord) receivers.get(k)).receiver == receiver) {receivers.remove(k);k--;}}if (receivers.size() <= 0)this.mActions.remove(action);}}}}}

Simply put, BroadcastReceiver is removed from mReceivers and mActions. Because BroadcastReceiver is the key of mReceivers, it is easy to remove it. MActions is a little more complex and needs to be removed from mActions according to the IntentFilter array in BroadcastReceiver.

Do you still remember that the actions with the same name can correspond to different BroadcastReceiver during registration? note the following sentence: if (ReceiverRecord) receivers. get (k )). receiver = receiver). Yes, it only removes the current one and does not delete the BroadcastReceiver corresponding to the action.


Finally, the key public boolean sendBroadcast (Intent intent) method is used. The whole method is synchronized (this. mReceivers). Because the content of this method is too long, we will explain it in sections here:

String action = intent.getAction();String type = intent.resolveTypeIfNeeded(this.mAppContext.getContentResolver());Uri data = intent.getData();String scheme = intent.getScheme();Set categories = intent.getCategories();boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION ) != 0;

First, retrieve the intent parameters, except action, for comparison. If intent. FLAG_DEBUG_LOG_RESOLUTION is set for setFlag in Intent, some log information can be output.


Then, the ReceiverRecord corresponding to the intent action is retrieved from mActions.

ArrayList entries = (ArrayList) this.mActions.get(intent.getAction());ArrayList receivers = null;for (int i = 0; i < entries.size(); i++)

This section is the content in the for Loop:

ReceiverRecord receiver = (ReceiverRecord) entries.get(i);if (receiver.broadcasting) {} else {int match = receiver.filter.match(action, type, scheme,data, categories, "LocalBroadcastManager");if (match >= 0) {if (receivers == null) {receivers = new ArrayList();}receivers.add(receiver);receiver.broadcasting = true;} else {}}}

Here, if it is sending, nothing will be done. Otherwise, match the IntentFilter in the receiver. If the filter matches, set it to sending, that is, set the broadcasting variable to true. The significance is to avoid repeated sending.


Finally, add it to the ArrayList: this. mPendingBroadcasts. add (new BroadcastRecord (intent, receivers); Notify Handler and execute the executePendingBroadcasts () method.

if (receivers != null) {for (int i = 0; i < receivers.size(); i++) {((ReceiverRecord) receivers.get(i)).broadcasting = false;}this.mPendingBroadcasts.add(new BroadcastRecord(intent,receivers));if (!this.mHandler.hasMessages(MSG_EXEC_PENDING_BROADCASTS)) {this.mHandler.sendEmptyMessage(MSG_EXEC_PENDING_BROADCASTS);}return true;}

The executePendingBroadcasts () method is simple, that is, retrieve the BroadcastReceiver in the mPendingBroadcasts array (save its object in ReceiverRecord) and call its onReceive method.

private void executePendingBroadcasts() {while (true) {BroadcastRecord[] brs = null;synchronized (this.mReceivers) {int N = this.mPendingBroadcasts.size();if (N <= 0) {return;}brs = new BroadcastRecord[N];this.mPendingBroadcasts.toArray(brs);this.mPendingBroadcasts.clear();}for (int i = 0; i < brs.length; i++) {BroadcastRecord br = brs[i];for (int j = 0; j < br.receivers.size(); j++)((ReceiverRecord) br.receivers.get(j)).receiver.onReceive(this.mAppContext, br.intent);}}}

There is also a method sendBroadcastSync, which is usually not used. Here let's look at the source code:

public void sendBroadcastSync(Intent intent) {if (sendBroadcast(intent))executePendingBroadcasts();}

Here, add the source code of its internal class ReceiverRecord:

private static class ReceiverRecord {final IntentFilter filter;final BroadcastReceiver receiver;boolean broadcasting;ReceiverRecord(IntentFilter _filter, BroadcastReceiver _receiver) {this.filter = _filter;this.receiver = _receiver;}}

Summary:

1. When LocalBroadcastManager creates a single example for passing parameters, it does not need to worry about whether the context is activity or Application. It will get the tApplicationContext by itself.

2. LocalBroadcastManager is only applicable to inter-code scenarios, because it stores the BroadcastReceiver object and directly calls its onReceive method.

3. After LocalBroadcastManager registers a broadcast, when the Activity or Fragment does not need to be monitored, remember to cancel the registration. Note the following: registration and cancellation must be consistent in the lifecycle of activity or fragment, such as onResume and onPause.

4. Although LocalBroadcastManager supports registering multiple intentfilters for the same BroadcastReceiver, all the required actions should be put into one IntentFilter, that is, only one IntentFilter should be registered, this is my personal suggestion.

5. The broadcast action sent by LocalBroadcastManager can only interact with BroadcastReceiver registered in LocalBroadcastManager. If you encounter a broadcast sent through LocalBroadcastManager, The BroadcastReceiver on the other side does not respond. This is probably the cause.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.