Junior — Middle
Is it possible to create and register a Broadcast Receiver at runtime instead of through the manifest?
sobes.tech AI
Answer from AI
Yes, in Android, it is possible to create and register a BroadcastReceiver dynamically at runtime, not only through the manifest. This is done using the registerReceiver() method in code, usually in an Activity or Service. This approach allows the receiver to only receive broadcast messages while the component is active, which is convenient for resource saving and security.
Example of dynamic registration:
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Handle the received message
}
};
// Register
registerReceiver(receiver, new IntentFilter("android.intent.action.SOME_ACTION"));
// Don't forget to unregister
unregisterReceiver(receiver);
Unlike registration in the manifest, dynamically registered receivers only live as long as the component that registered them is active.