Is it necessary to register a BroadcastReceiver in the manifest file or can it be connected programmatically?
sobes.tech AI
Answer from AI
In Android, BroadcastReceiver can be registered in two ways:
-
In the manifest (statically) — this method allows the system to know about the receiver even if the application is not running. It is convenient for receiving broadcast messages that should launch the app or perform actions in the background.
-
Programmatically (dynamically) — registration occurs in code, usually in the lifecycle methods of an Activity or Service. This method provides more control: the receiver is active only while registered, which helps save resources and prevent leaks.
The choice of method depends on the task. For example, system-wide broadcast messages that need to be processed always are registered in the manifest. For local or temporary events — programmatic registration.
Example of programmatic registration:
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// handle event
}
};
// Register
registerReceiver(receiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
// Unregister
unregisterReceiver(receiver);