Broadcast Mechanism: Standard broadcast, ordered broadcast, local broadcast, broadcast mechanism Standard

Source: Internet
Author: User

Broadcast Mechanism: Standard broadcast, ordered broadcast, local broadcast, broadcast mechanism Standard
Send standard Broadcast

Define a broadcast receiver to prepare to receive this broadcast, and create a new MyBroadcastReceiver inherited from BroadcastReceiver

import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.widget.Toast;public class MyBroadcastReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        Toast.makeText(context, "received in MyBroadcastReceiver", Toast.LENGTH_SHORT).show();    }}

Register the broadcast receiver in AndroidManifest. xml

             
                              
          
 

Layout File

 
  
 

Activity

import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;public class Test extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_test);        Button button = (Button) findViewById(R.id.button);        button.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Intent intent = new Intent("com.example.xx.MY_BROADCAST");                sendBroadcast(intent);            }        });    }}

Running result:
When MyBroadcastReceiver receives a custom broadcast, the receivedinMyBroadcastReceiver prompt appears.


Code explanation

When registering in AndroidManifest. xml, let MyBroadcastReceiver receive a broadcast with the value com. example. xx. MY_BROADCAST. Therefore, when sending a broadcast later, we need to issue such a broadcast.

We added the logic for sending custom broadcasts to the button click event. First, an Intent object is constructed, and the value of the broadcast to be sent is passed in. Then, the sendBroadcast () method of Context is called to send the broadcast, so that all the listeners are com. example. xx. the broadcast receiver of MY_BROADCAST receives the message. The broadcast sent out is a standard broadcast.

Send ordered Broadcast

Other applications should also be able to receive broadcasts from our applications. To verify this, we need to create another BroadcastTest2 project.

After creating a project, you also need to define a broadcast receiver under this project to receive custom broadcasts in the previous section. New AnotherBroadcastReceiver inherits from BroadcastReceiver

import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.widget.Toast;public class AnotherBroadcastReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        Toast.makeText(context, "received in AnotherBroadcastReceiver", Toast.LENGTH_SHORT).show();    }}

AndroidManifest. xml Registration

             
                              
          
 

AnotherBroadcastReceiver receives the broadcast com. example. xx. MY_BROADCAST in the same sample. Run the BroadcastTest2 project to install the program on the simulator. Then return to the main interface of the BroadcastTest project and click the SendBroadcast button. Two prompts are displayed.

This strongly proves that the broadcast sent by our application can be received by other applications. So far, all the messages in the program are still standard broadcasts.

Now let's try to send an ordered broadcast. Disable the BroadcastTest2 project and modify the code in MainActivity.

public class Test extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_test);        Button button = (Button) findViewById(R.id.button);        button.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Intent intent = new Intent("com.example.xx.MY_BROADCAST");                sendOrderedBroadcast(intent,null);            }        });    }}

Running result:
Run the program again and click the SendBroadcast button. You will find that both applications can still receive this broadcast.

Code explanation
The sendOrderedBroadcast () method receives two parameters. The first parameter is still Intent, and the second parameter is a permission-related string. Here, null is passed in.

It seems that there is no difference with standard broadcast, but don't forget that at this time, the broadcast receiver is sequential, and the previous broadcast receiver can also cut the broadcast, to prevent further propagation

How can we set the sequence of broadcast receivers? Of course it was set during registration. modify the code in AndroidManifest. xml.

             
                              
          
     

We can see that we set the broadcast receiver priority through the android: priority attribute. The broadcast receiver with a higher priority can receive the broadcast first. Set the priority of MyBroadcastReceiver to 100 to ensure that it will receive the broadcast before AnotherBroadcastReceiver.

Now that you have obtained the broadcast receiving priority, MyBroadcastReceiver can choose whether to allow broadcasting to continue. Modify the code in MyBroadcastReceiver and add

abortBroadcast();

If the abortBroadcast () method is called in the onReceive () method, the broadcast is truncated and the subsequent broadcast receiver cannot receive the broadcast. Run the program again and click the SendBroadcast button. Only the Toast information in MyBroadcastReceiver can be displayed, indicating that the broadcast is terminated after MyBroadcastReceiver.

Use local broadcast

All the broadcasts we send and receive are system global broadcasts, that is, the broadcast can be received by any other application, we can also receive broadcasts from any other application. This will easily cause security issues. For example, some broadcasts we send that carry key data may be intercepted by other applications, or other programs keep sending various Spam broadcasts to our broadcast receivers.

In order to solve the broadcast security problem simply, Android introduces a local broadcast mechanism. The broadcast sent by this mechanism can only be transmitted within the application, in addition, the broadcast receiver can only receive broadcasts from this application, so that all security issues do not exist.

The usage of local broadcast is not complex. It mainly uses a LocalBroadcastManager to manage the broadcast, and provides methods to send broadcast and register broadcast receivers. Next we will try its usage through a specific instance.

Modify the code in MainActivity

Import android. content. broadcastReceiver; import android. content. context; import android. content. intent; import android. content. intentFilter; import android. support. v4.content. localBroadcastManager; import android. support. v7.app. appCompatActivity; import android. OS. bundle; import android. view. view; import android. widget. button; import android. widget. toast; public class Test extends AppCompatActivity {private IntentFilter intentFilter; private LocalReceiver localReceiver; private LocalBroadcastManager localBroadcastManager; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_test); localBroadcastManager = LocalBroadcastManager. getInstance (this); Button button = (Button) findViewById (R. id. button); button. setOnClickListener (new View. onClickListener () {@ Override public void onClick (View view) {Intent intent = new Intent ("com. example. xx. LOCAL_BROADCAST "); localBroadcastManager. sendBroadcast (intent); // send local broadcast}); intentFilter = new IntentFilter (); intentFilter. addAction ("com. example. xx. LOCAL_BROADCAST "); localReceiver = new LocalReceiver (); // register the local broadcast listener localBroadcastManager. registerReceiver (localReceiver, intentFilter);} class LocalReceiver extends BroadcastReceiver {@ Override public void onReceive (Context context, Intent intent) {Toast. makeText (context, "received local broadcast", Toast. LENGTH_SHORT ). show () ;}@ Override protected void onDestroy () {super. onDestroy (); localBroadcastManager. unregisterReceiver (localReceiver );}}

Code explanation

In fact, this is basically the same as the previous dynamic registration of the broadcast receiver and the Code for sending the broadcast. However, the getInstance () method of LocalBroadcastManager is used to obtain an instance of LocalBroadcastManager, and then the registerReceiver () method of LocalBroadcastManager is called when registering the broadcast receiver, when sending a broadcast, the sendBroadcast () method of LocalBroadcastManager is called. That's all.

Here, we send a com. example. xx. LOCAL_BROADCAST broadcast in the Click Event of the button, and then receive the broadcast in LocalReceiver. Run the program again and click Send Broadcast. The Toast prompt is displayed.

If you are still interested in the experiment, you can try to receive com. example. xx. the answer to the LOCAL_BROADCAST broadcast is obvious and cannot be received, because the broadcast will only spread in the BroadcastTest program.

Note:
Local broadcasts cannot be received through static registration. In fact, this is completely understandable, because static registration is mainly used to enable the program to receive broadcasts even if it is not started. When sending a local broadcast, our program must have been started, therefore, static registration is not required at all.

Finally, let's take a look at the advantages of using local broadcast.
1. We can clearly understand that the broadcast being sent will not leave our program, so we do not need to worry about the leakage of confidential data.
2. Other programs cannot send broadcasts to our programs. Therefore, you do not need to worry about security vulnerabilities.
3. Sending local broadcasts is more efficient than sending system global broadcasts.

Related Article

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.