Sobes.tech
Junior — Middle

Can you explain what the BroadcastReceiver component in Android is and how it is used?

sobes.tech AI

Answer from AI

BroadcastReceiver in Android is a component that allows an application to receive and respond to broadcast messages from the system or other applications. These messages can signal various events, such as connecting to a charger, changing network state, receiving an SMS, etc.

Using BroadcastReceiver:

  • It is registered either statically in the manifest or dynamically in code.
  • When the corresponding broadcast is received, the onReceive() method is called, where necessary actions can be performed.

Example of dynamic registration of BroadcastReceiver to monitor network connectivity:

BroadcastReceiver networkReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Handle network state change event
    }
};

IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(networkReceiver, filter);

BroadcastReceiver is useful for responding to system events without keeping the app running constantly in the background.

Can you explain what the BroadcastReceiver component… - sobes.tech