Sobes.tech
Junior — Middle

How do registration methods differ if using static or dynamic approach for BroadcastReceiver?

sobes.tech AI

Answer from AI

Static registration of BroadcastReceiver occurs through declaration in AndroidManifest.xml. Such a receiver is always active when the application is installed and can receive system broadcast messages even if the application is not running.

Dynamic registration is performed programmatically in code (usually in an Activity or Service) using the registerReceiver() method. Such a receiver is only active while registered (for example, while the Activity is active) and is automatically unregistered when unregisterReceiver() is called.

Main differences:

  • Static receiver:

    • Registered in the manifest.
    • Always works, even if the application is not running.
    • Suitable for system events.
  • Dynamic receiver:

    • Registered and unregistered in code.
    • Works only during registration.
    • Allows flexible management of lifecycle.

Example of dynamic registration:

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

@Override
protected void onResume() {
    super.onResume();
    registerReceiver(receiver, new IntentFilter("android.intent.action.SOME_ACTION"));
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(receiver);
}

Thus, the choice of registration method depends on the requirements for the receiver's lifecycle and the context of use.