Junior — Middle
At what part of the Android BroadcastReceiver lifecycle is the onReceive method activated?
sobes.tech AI
Answer from AI
The onReceive method in Android BroadcastReceiver is activated at the moment when the system receives the corresponding broadcast message. This occurs in the following part of the lifecycle:
- When the system or another application sends a broadcast Intent, the registered BroadcastReceiver receives this Intent.
- In response to receiving the Intent, the
onReceive(Context context, Intent intent)method is called.
It is important to note that onReceive is called only during the processing of a specific broadcast message and executes quickly, as the system may terminate the application process after the method completes if the app is not active.
Example of a simple BroadcastReceiver:
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Handling the received broadcast
String action = intent.getAction();
if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
// Actions after device boot
}
}
}
Thus, onReceive is activated directly upon receiving a broadcast message and serves as the entry point for handling this event.