Junior
What is BroadcastReceiver in Android?
sobes.tech AI
Answer from AI
This is a component that responds to system or user broadcast messages. It has no user interface and is designed to perform background operations in response to specific events.
Main characteristics:
- Responds to Intents with a specific action.
- Short-lived component, its
onReceive()method executes for a brief period. - Not intended for long operations. If long-running work is needed, a Service should be started from
onReceive(). - Can be registered statically in the manifest or dynamically in code.
Examples of usage:
- Responding to network state changes (
android.net.conn.CONNECTIVITY_CHANGE). - Responding to system boot (
android.intent.action.BOOT_COMPLETED). - Handling incoming SMS.
- Receiving custom messages sent by other components or applications.
Registration in the manifest:
<receiver android:name=".MyBroadcastReceiver"
android:exported="true"> // exported="true" so other apps can send intents
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
Registration in code:
// In Activity or Service
IntentFilter filter = new IntentFilter("com.example.MY_CUSTOM_ACTION");
MyBroadcastReceiver receiver = new MyBroadcastReceiver();
registerReceiver(receiver, filter);
// In onDestroy() or onStop() - it's important to unregister!
unregisterReceiver(receiver);
BroadcastReceiver class:
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Code executed upon receiving an Intent
// For example:
if ("com.example.MY_CUSTOM_ACTION".equals(intent.getAction())) {
Toast.makeText(context, "Received custom action!", Toast.LENGTH_SHORT).show();
}
}
}