How to set up the registerReceiver in Android Broadcast?

To receive broadcast messages in an Android application using a BroadcastReceiver, you need to register the BroadcastReceiver in the code. Here is one method of setting up registerReceiver:

  1. Create a BroadcastReceiver class and implement the onReceive method, which is used to handle received broadcast messages.
public class MyBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // 处理接收到的广播消息
    }
}
  1. Register a BroadcastReceiver in Activity or Service, specifying the type of broadcast message to receive.
MyBroadcastReceiver myReceiver = new MyBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.example.broadcast.MY_ACTION");

registerReceiver(myReceiver, intentFilter);
  1. Declare a BroadcastReceiver and its corresponding broadcast message type in the Manifest file.
<receiver android:name=".MyBroadcastReceiver">
    <intent-filter>
        <action android:name="com.example.broadcast.MY_ACTION" />
    </intent-filter>
</receiver>

By following the above steps, you can use a BroadcastReceiver in an Android application to receive broadcast messages and perform corresponding actions. It is important to unregister the BroadcastReceiver when not needed to avoid memory leaks.

bannerAds