Basic knowledge of android component broadcast

Posted by newcastle_unite on Tue, 09 Jun 2020 07:08:41 +0200

The last blog recorded the basic knowledge of activity. This blog recorded the basic knowledge of Broadcast

radio broadcast
Broadcast is a mechanism to transfer information between applications. It can transfer information between different programs or within the same program.
Broadcast Receiver is used to receive broadcast.
Each application in android can register the broadcast that it is interested in, so that the application can only focus on the content it cares about.

Type of broadcast
There are four types of Broadcasting: Standard broadcasting, ordered broadcasting, local broadcasting and sticky broadcasting
(1) Standard broadcast: it is a completely asynchronous broadcast. After the broadcast is sent, all broadcast receivers will receive the broadcast message almost at the same time. The efficiency of standard broadcasting is high, but it also means that it cannot be cut off.
(2) Orderly broadcast: it is a synchronous broadcast. Only one broadcast receiver can receive the broadcast message at the same time after the broadcast is sent. Only after the logic processing in the receiver is completed can it continue to deliver. The higher priority receiver receives the broadcast first and the front broadcast receiver can truncate the broadcast being delivered.
(3) Local broadcast: the broadcast from local broadcast can only be delivered within the application, and the broadcast receiver can only receive the broadcast from this application. It effectively solves the security problem of broadcasting. Mainly use local broadcast manager to manage broadcast
(4) Sticky broadcast: sticky broadcast will be stuck all the time. When a receiver matching the broadcast is registered, the receiver will receive the broadcast.

Use of broadcast
Standard broadcast
(1) Receiving system broadcast
To use broadcast, you need to create a broadcast receiver first. Create method: create a new class, inherit from BroadcastReceiver, and override onReceive() method.
When a broadcast arrives, the onReceiver() method will execute and the specific logic will be processed in it. But you can't add too much logic or any time-consuming operation to the onReceiver() method, because it's not allowed to start a thread in the broadcast receiver. When onReceiver() runs for too long, the program will report an error.
The broadcast receiver also needs to register the broadcast in which it is interested so that the broadcast receiver can receive the broadcast. There are two ways to register: dynamic (register in code) and static (register in AndroidManifest.xml Registered in).
The difference between static registration and dynamic registration is that dynamic registration can only receive broadcast after the program is started; static registration can receive broadcast when the program is not started.
For example: suppose we want to monitor the network changes in the system
First, create a NetworkChangeReceiver class that inherits from the BroadcastReceiver, override the onReceive() method, and write the logic you want to implement in onReceive().
Then: dynamic registration or static registration
Dynamic registration:
1. Override the onCreate() method and add the registerReceiver() method
2. Override the onDestroy() method and add the unregisterReceiver() method
Static registration:
stay AndroidManifest.xml Add code in

<receiver
	android:name = "." //Fill in your class name
	<intent-filter>
		<action android:name = " "/> //Fill in the broadcast you want to send
	</intent-filter>
</receiver>

Specific code implementation:

	//1. Create a NetworkChangeReceiver class that inherits from BroadcastReceiver and overrides the onReceive() method
    class NetworkChangeReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context , Intent intent){
            Toast.makeText(context , "Network change", Toast.LENGTH_SHORT).show();
        }
    }
//Dynamic registration
public class MainActivity extends AppCompatActivity {
    private IntentFilter intentFilter;
    private NetworkChangeReceiver networkChangeReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        networkChangeReceiver = new NetworkChangeReceiver();
        //2. Add registerReceiver() method
        registerReceiver(networkChangeReceiver , intentFilter);
    }

	//3. Override onDestroy() method
    @Override
    protected void onDestroy(){
        super.onDestroy();
        unregisterReceiver(networkChangeReceiver);
    }
}

(2) Send custom broadcast
Before sending a custom broadcast, we need to define a broadcast receiver to receive the secondary broadcast. Then we build a Intent object to transmit the broadcast value to be sent, then call the sendBroadcast() method of Context to broadcast the broadcast.

//Define a broadcast receiver
public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        Toast.makeText(context , "This is a custom broadcast" , Toast.LENGTH_SHORT).show();
    }
}
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.example.New2.MY_BROADCAST");
                sendBroadcast(intent);
            }
        });
    }
//stay AndroidManifest.xml Registered in
  <receiver
            android:name=".MyReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.example.New2.MY_BROADCAST"/>
            </intent-filter>
  </receiver>

Orderly broadcasting
The broadcasting receivers of orderly broadcasting have sequence, and the broadcasting receivers in front can stop the broadcasting from continuing. These are set at the time of registration.
Just change sendBroadcast() to sendOrderedBroadcast(). sendOrderedBroadcast() receives two parameters, the first is Intent, and the second is a permission related string. Here, null is passed in.
For example:

Intent intent = new Intent("com.example.New2.MY_BROADCAST");
sendOrderedBroadcast(intent,null); //Send an orderly broadcast
<intent-filter android:priority="100"> //add permission
      <action android:name="com.example.New2.MY_BROADCAST"/>
</intent-filter>

If you want to intercept the broadcast, the broadcast will continue to propagate, as long as the abortBroadcast() method can be invoked in the onReceive() method that broadcasts the receiver ahead.

 public void onReceive(Context context, Intent intent) {
        Toast.makeText(context , "This is a custom broadcast" , Toast.LENGTH_SHORT).show();
        abortBroadcast();//Cut off the broadcast. The receiver behind will not receive the broadcast
    }

Local broadcast
The security of the broadcast has not been resolved. We can use local broadcast.
Local broadcast mainly uses local broadcast manager to manage the broadcast, and provides methods of sending broadcast and registering broadcast receiver.
First, get an instance through the getInstance() method of loadbroadcastmanger;
Then, the registerReceiver() method of LocalBroadManger is called when registering the broadcast receiver, and the sendBroadcast() method of LocalBroadManger is called when sending the broadcast
For example:

//Customize a local broadcast receiver
public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        Toast.makeText(context , "This is a local broadcast" , Toast.LENGTH_SHORT).show();
    }
}
 	private Button button;
    private IntentFilter intentFilter;
    private LocalBroadcastManager localBroadcastManager;
    private MyReceiver myReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        localBroadcastManager = LocalBroadcastManager.getInstance(this); // Get instance

        button = findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.example.New2.MY_BROADCAST");
                localBroadcastManager.sendBroadcast(intent); //Send local broadcast
            }
        });
        //Dynamic registration, local registration cannot be done through static registration
        intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.New2.MY_BROADCAST");
        myReceiver = new MyReceiver();
        localBroadcastManager.registerReceiver(myReceiver , intentFilter);
    }

Local broadcasting can't be carried out by static registration, because: static registration is mainly to let the program receive broadcasting even when it is not started, and our program must have started when sending local broadcasting.
Advantages of local broadcasting:
(1) Clear broadcast will not leave our program, ensuring data security
(2) Other broadcasts can't be sent to our program, so we don't need to worry about security vulnerabilities
(3) Sending local broadcast is more effective than global broadcast

Topics: Android xml network