0 votes
in Android Library by
Can you explain the concept of a BroadcastReceiver in Android and provide an example of when you would use it?

1 Answer

0 votes
by
A BroadcastReceiver in Android is a component that responds to system-wide or app-specific events, known as Intents. It allows apps to react to changes without running continuously, conserving resources. BroadcastReceivers are registered either statically via the manifest file or dynamically through code.

A common use case for BroadcastReceiver is monitoring network connectivity. When an app requires internet access, it can register a BroadcastReceiver to listen for connectivity changes and respond accordingly. For example, if the device loses connection, the app could pause data syncing until reconnected.

Example:

public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override

    public void onReceive(Context context, Intent intent) {

        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {

            boolean isConnected = !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);

            // Handle connectivity change: pause/resume syncing

        }

    }

}

Register in manifest:

<receiver android:name=".NetworkChangeReceiver">

    <intent-filter>

        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />

    </intent-filter>

</receiver>

Related questions

0 votes
asked Aug 30, 2023 in Android Library by SakshiSharma
0 votes
asked Aug 30, 2023 in Android Library by SakshiSharma
...