How to use Broadcast receivers in an Android app?

Broadcast receivers in Android allow applications to respond to broadcast messages from other applications or from the system itself. They are primarily used to listen for system-wide events, such as changes in network connectivity, battery level changes, or when a device starts up. This can greatly enhance the functionality and responsiveness of mobile applications.

How to Use Broadcast Receivers

To use a BroadcastReceiver in your Android app, follow these steps:

  1. Create a new class that extends the BroadcastReceiver class.
  2. Override the onReceive method to define the behavior when the broadcast is received.
  3. Register the receiver in your app's manifest or at runtime.
  4. Handle the broadcast in your app.

Example of a Broadcast Receiver

The following is an example of a broadcast receiver that listens for changes in connectivity:

<?php class ConnectivityReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); // Handle the network change if (isConnected) { // Connection is available } else { // No connection } } } ?>

BroadcastReceiver Android app system events network connectivity Android development mobile applications