Junior — Middle
How to implement the start of a BroadcastReceiver in an Android application?
sobes.tech AI
Answer from AI
There are two main ways to work with BroadcastReceiver in Android:
- Static registration in the manifest — added to
AndroidManifest.xml. Such a receiver will receive broadcast messages even if the app is not running.
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
- Dynamic registration in code — registered in an activity or service using
registerReceiver(). Works only while the app is active.
BroadcastReceiver receiver = new MyBroadcastReceiver();
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(receiver, filter);
The choice of method depends on the task: for system events that need to be caught always — static registration, for temporary ones — dynamic.