Sobes.tech
Junior — Middle

How to implement the reception and processing of broadcast messages in an Android application?

sobes.tech AI

Answer from AI

The class BroadcastReceiver is used for receiving and handling broadcast messages in an Android application.

Main steps:

  1. Create a class that extends BroadcastReceiver and override the onReceive(Context context, Intent intent) method.
  2. Register the receiver:
    • Statistically — in the manifest (AndroidManifest.xml) with an intent filter (<intent-filter>).
    • Dynamically — in code using registerReceiver() with a filter.

Example of dynamic registration:

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Handle message
        String action = intent.getAction();
        if ("android.net.conn.CONNECTIVITY_CHANGE".equals(action)) {
            // React to connectivity change
        }
    }
}

// In Activity or Service
MyReceiver receiver = new MyReceiver();
IntentFilter filter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(receiver, filter);

// Don't forget to unregister
unregisterReceiver(receiver);

Note that starting from Android 8.0 (API 26), many broadcast messages cannot be received via static registration in the manifest; it is recommended to use dynamic registration.

Thus, receiving broadcast messages is implemented through BroadcastReceiver and registration of appropriate filters.