BroadcastReceiver broadcast receiver

Posted by laPistola on Wed, 05 Jan 2022 12:01:25 +0100

BroadcastReceiver broadcast receiver

BroadcastReceiver is to facilitate the communication between various applications and internal programs of Android system. Android system introduces a set of broadcasting mechanism. Each application can register the broadcast of interest. When the system or other programs send the broadcast, the program that has registered the broadcast can receive the broadcast. There is a complete API in Android system, which allows programs to send and receive broadcasts only.
Note: do not handle too much logic or perform any operation that takes too long in the broadcast, because threads are not allowed to be started in the broadcast; When the onReceiver() method runs for more than 10S and is not finished, the program will report an error (ANR). When broadcasting, it plays the role of opening other components, such as starting Service,Notification prompt, Activity, etc.

There are two main types of broadcasting in Android system:
1. Normal Broadcasts
It is a completely asynchronous broadcast. After the broadcast, all broadcast receivers will receive the broadcast at the same time, and the broadcast cannot be truncated.
Sending method:

Intent intent = new Intent("com.example.servicedemo.BORADCAST_TEST");
	sendBroadcast(intent);

2. Ordered Broadcasts:
It is a synchronously executed broadcast. After the broadcast is sent, the broadcast receiver with high priority can receive the broadcast first, and can cut off and stop the broadcast before the broadcast receiver with low priority receives it.
Sending method:

Intent intent = new Intent("com.example.servicedemo.BORADCAST_TEST");
	//The second parameter is a permission related string
	sendoradeBroadcast(intent,null);

Broadcast registration:
In the broadcast receiving mechanism of Android, if you need to receive a broadcast, you need to create a broadcast receiver. The way to create a broadcast receiver is to create a new class (either a separate class or an internal class) to inherit BraadcastReceiver, and then use.

public class MyBroadcast extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

    }
}

The difference between dynamic registration and static registration
The dynamically registered broadcast receiver can freely control registration and cancellation, which has great flexibility. However, the broadcast can only be received after the program is started. The logoff of the broadcast receiver is in the onDestroy() method. The life cycle of all broadcast receivers is the same as that of activities.
The statically registered broadcast is not constrained by whether the program is started or not. The broadcast can still be received after the program is closed.

There are two ways to register a broadcast:
Dynamic registration
To register in the code, the steps are as follows:
1. Instantiate a custom broadcast receiver.
2. Create an IntentFilter instance.
3. Call the addAction() method of the IntentFilter instance to add the listening broadcast type.
4. finally, call Context's registerReceiver(BroadcastReceiver, IntentFilter) registered broadcast.
Note: if you need to receive the system broadcast (power change, network change, etc.), you need to add permissions in the AndroidManifest.xml file!!!

Static registration

<receiver android:name=".MyBroadcastReceiver">
       <intent-filter>
          <action android:name="com.example.MY_BROADCAST"></action>
       </intent-filter>
</receiver>

Dynamic registration broadcast example:
1. Registered broadcasting

public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e("MyBroadcast","onReceive()");
    }
}

2. Register broadcast receiver

public class MainActivity extends AppCompatActivity {

    private MyBroadcastReceiver myBroadcastReceiver;
    private Button button ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Dynamically register broadcast receivers
        myBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.broadcastdemo.MyBroadcastReceiver");
        registerReceiver(myBroadcastReceiver,intentFilter);
             
        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,SecondActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //Log off broadcast
        unregisterReceiver(myBroadcastReceiver);
        Log.e("Log off broadcast---------","unregisterReceiver");

    }
}

3. Send broadcast in SecondActivity

public class SecondActivity extends AppCompatActivity {
    private Button button2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        button2 = findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.example.broadcastdemo.MyBroadcastReceiver");
                sendBroadcast(intent);
            }
        });
    }
}


Description broadcast received in MainActivity.

Static registration broadcast example:
1. (ibid., 1)
2. Registered receiver (ditto 2)

//Dynamically register broadcast receivers
        myBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.broadcastdemo.MyBroadcastReceiver");
        registerReceiver(myBroadcastReceiver,intentFilter);

3. Send broadcast

public class SecondActivity extends AppCompatActivity {
    private Button button2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        button2 = findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Send broadcast
                // Android 8.0 and above systems no longer support this method.
//                Intent intent = new Intent("com.example.broadcastdemo.MyBroadcastReceiver");
                Intent intent = new Intent();
                intent.setComponent(new ComponentName(SecondActivity.this,MyBroadcastReceiver.class));
                sendBroadcast(intent);
            }
        });
    }
}

4. On Android manifest Register in XML

<receiver android:name=".MyBroadcastReceiver">
        <intent-filter>
            <action android:name="com.example.broadcastdemo.MyBroadcastReceiver"></action>
        </intent-filter>
</receiver>

Topics: Android