Sobes.tech
Junior — Middle

How do dynamic and static registration methods of BroadcastReceiver differ in Android?

sobes.tech AI

Answer from AI

In Android, there are two ways to register a BroadcastReceiver — static and dynamic.

Static registration is done in the application's manifest (AndroidManifest.xml). Such a receiver is activated by the system even if the application is not running. It is convenient for listening to system broadcast messages, but starting from Android 8.0 (Oreo), static registration for most events is limited.

Dynamic registration is done programmatically in the code (usually in an Activity or Service) using the registerReceiver() method. Such a receiver is active only as long as the object in which it is registered exists, and it requires an explicit call to unregisterReceiver(). Dynamic registration is more flexible and allows listening to broadcast messages only during the component's runtime.

Example of dynamic registration:

BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // handle event
    }
};

// In onCreate() or onStart()
registerReceiver(receiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

// In onDestroy() or onStop()
unregisterReceiver(receiver);