Sobes.tech
Junior — Middle

What are the differences between the dynamic and static mechanisms of Broadcast Receiver in Android?

sobes.tech AI

Answer from AI

In Android, there are two ways to register a Broadcast Receiver: static and dynamic.

Static Broadcast Receiver:

  • Registered in the application's manifest (AndroidManifest.xml).
  • It triggers even if the application is not running.
  • Used to receive broadcast messages from the system or other applications.
  • Minus: starting from Android 8.0 (API 26), many system broadcast messages cannot be received statically to save resources.

Dynamic Broadcast Receiver:

  • Registered programmatically in code using registerReceiver().
  • Active only while the application or component (e.g., Activity) is alive.
  • Allows more flexible management of the receiver's lifecycle.
  • Can be registered and unregistered at needed moments.

Summary:

  • Static receiver — always active, registered in the manifest.
  • Dynamic — active only during the application's runtime, registered in code.

Example of dynamic registration:

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

@Override
protected void onStart() {
    super.onStart();
    IntentFilter filter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
    registerReceiver(receiver, filter);
}

@Override
protected void onStop() {
    super.onStop();
    unregisterReceiver(receiver);
}
What are the differences between the dynamic and… - sobes.tech