Differences between local broadcast and global broadcast and their implementation principles
I. Differences between local broadcast and global broadcast
1. Local broadcast: broadcast events sentNot obtained by other applications, AlsoCannot respond to broadcast events sent by other applications. Local BroadcastCan only be dynamically registeredStatic registration is not allowed. Dynamic Registration or method is requiredLocalBroadcastManager.
2. Global broadcast: broadcast events sentCan be obtained by other applications, Can alsoResponds to broadcast events sent by other applications(It can be controlled through exported-whether to listen to broadcasts sent by other applications in the list file) global broadcastYou can register dynamically or statically.
Ii. basic use of local broadcast
/* Click the Button to send the local broadcast */public class BroadcastActivity extends AppCompatActivity {private static final String TAG = "TAG"; // TAG private LocalBroadcast localBroadcast; // private Button mBtStart for local broadcast; // Button @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_broadcast); mBtStart = findViewById (R. id. bt_start); mBtStart. setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {LocalBroadcastManager. getInstance (BroadcastActivity. this ). sendBroadcast (new Intent ("com. hbbfxy. localbroadcast "); // send local broadcast});/* Register broadcast */localBroadcast = new LocalBroadcast (); IntentFilter intentFilter = new IntentFilter (); intentFilter. addAction ("com. hbbfxy. localbroadcast "); LocalBroadcastManager. getInstance (this ). registerReceiver (localBroadcast, intentFilter);} private class LocalBroadcast extends BroadcastReceiver {@ Override public void onReceive (Context context, Intent intent) {Log. e (TAG, "onReceive:") ;}@ Override protected void onDestroy () {super. onDestroy (); LocalBroadcastManager. getInstance (this ). unregisterReceiver (localBroadcast); // contact registered broadcast }}
Iii. Implementation principle of local broadcast
Through the basic use of local broadcast, we know the main difference between local broadcast and global broadcast in form.LocalBroadcastManager class. So if you want to understand the implementation principle of local broadcast, you can look at this class.
Next we will learn about the internal implementation through the main method.
1. LocalBroadcastManager. getInstance (this) // instantiate the local broadcast Manager
/* In singleton mode, maintain a copy of data in the process */private static LocalBroadcastManager mInstance; public static LocalBroadcastManager getInstance (Context context) {synchronized (mLock) {if (mInstance = null) {mInstance = new LocalBroadcastManager (context. getApplicationContext ();} return mInstance;} private LocalBroadcastManager (Context context) {// initialize the environment mAppContext = context; // Handler 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 );}}};}
Before learning about other methods, let's take a look at the two internal data classes (ReceiverRecord and BroadcastRecord) and three data sets of the LocalBroadcastManager class.
Private static final class ReceiverRecord {// record the current intent to filter the final IntentFilter filter; // record the current broadcast receiver final BroadcastReceiver receiver; // whether the current broadcast receiver is broadcasting boolean broadcasting; // whether to disable boolean dead; ReceiverRecord (IntentFilter _ filter, BroadcastReceiver _ receiver ER) {filter = _ filter; receiver ER = _ receiver er ;}}
Private static final class BroadcastRecord {// record the current Intent final intent Intent; // record the data structure final ArrayList that conforms to the current intent
Receivers; BroadcastRecord (Intent _ intent, ArrayList
_ Receivers) {intent = _ intent; receivers = _ receivers ;}}
// Record the private final HashMap of all broadcasts currently registered
> MReceivers = new HashMap <> (); // record the broadcast private final HashMap that currently has an Action
> MActions = new HashMap <> (); // record the broadcast private final ArrayList currently awaiting execution
MPendingBroadcasts = new ArrayList <> ();
2. LocalBroadcastManager. getInstance (this)
. RegisterReceiver (localBroadcast, intentFilter); // register Broadcast
Public void registerReceiver (BroadcastReceiver receiver, IntentFilter filter) {synchronized (mReceivers) {/* matches the broadcast receiver with the corresponding intent filter. Note: A broadcast receiver may have multiple intent filters. */ReceiverRecord entry = new ReceiverRecord (filter, recycler); ArrayList
Filters = mReceivers. get (receiver ER); if (filters = null) {filters = new ArrayList <> (1); mReceivers. put (author er, filters);} filters. add (entry); // match the Action in the intent filter with the corresponding broadcast receiver. Note: an Action may correspond to multiple broadcast recipients for (int I = 0; I
Entries = mActions. get (action); if (entries = null) {entries = new ArrayList
(1); mActions. put (action, entries) ;}entries. add (entry );}}}
3. LocalBroadcastManager. getInstance (this)
. UnregisterReceiver (localBroadcast); // unregister a local broadcast.
Public void unregisterReceiver (BroadcastReceiver receiver) {synchronized (mReceivers) {// deletes the specified broadcast and returns all intent filters for the specified broadcast. Final ArrayList
Filters = mReceivers. remove (receiver ER); if (filters = null) {return;}/* traverse all intent filters for the specified broadcast */for (int I = filters. size ()-1; I> = 0; I --) {final ReceiverRecord filter = filters. get (I); // mark that the current broadcast hangs the filter. dead = true;/* traverse all actions of the filtering intent */for (int j = 0; j
Receivers = mActions. get (action); if (receivers! = Null) {for (int k = receivers. size ()-1; k> = 0; k --) {final ReceiverRecord rec = receivers. get (k);/* if a specified broadcast in the mAction list is to be deleted, mark the broadcast in the mAction list as suspended */if (rec. operator ER = Operator ER) {rec. dead = true; receivers. remove (k) ;}} if (receivers. size () <= 0) {mActions. remove (action );}}}}}}
4. LocalBroadcastManager. getInstance (BroadcastActivity. this)
. SendBroadcast (new Intent ("com. hbbfxy. localbroadcast"); // send Broadcast
Public boolean sendBroadcast (Intent intent) {synchronized (mReceivers) {/* Get the filtering information in the intent */final String action = Intent. getAction (); // Action final String type = intent. resolveTypeIfNeeded (// Type mAppContext. getContentResolver (); final Uri data = intent. getData (); // URI final String scheme = intent. getScheme (); // scheme final Set
Categories = intent. getCategories (); // type // obtain all broadcast recipients in the mAction list ArrayList based on the Action in the intent
Entries = mActions. get (intent. getAction (); if (entries! = Null) {// Save the intended broadcast receiver ArrayList
Receivers = null;/* traverse the broadcast receiver */for (int I = 0; I
= 0) {if (receivers = null) {receivers = new ArrayList
();}/* If the broadcast receiver meets the intent, save and mark the broadcast */receivers. add (worker ER); worker er. broadcasting = true;} else {}}/* traverses the intended broadcast receiver and marks it as set to broadcast end */if (receivers! = Null) {for (int I = 0; I
Finally, the main thread Handler built in the constructor sends messages and executes the executePendingBroadcasts () method.
/* Broadcast sending waiting for execution */private void executePendingBroadcasts () {for (int j = 0; j
Through the source code analysis, we know that the local broadcastThe implementation principle is to use HashMap and List to maintain the relationship among the broadcast receiver, IntentFileter, and Intent.
Learning Experience: viewing materials + thinking questions + proof of Practice + summarizing and summarizing + sorting records = Thinking Skills