How to integrate Broadcast receivers with other Android components?

Integrating Broadcast Receivers with other Android components is essential for building responsive and interactive applications. Broadcast Receivers allow your application to listen for and respond to events that occur in the system or in other applications, making them a powerful component for seamless communication.

Example of Integrating Broadcast Receiver

Below is a simple example demonstrating how to register a Broadcast Receiver to listen for connectivity changes in your Android application:

// MainActivity.java public class MainActivity extends AppCompatActivity { private ConnectivityReceiver connectivityReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize the receiver connectivityReceiver = new ConnectivityReceiver(); } @Override protected void onStart() { super.onStart(); IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(connectivityReceiver, filter); } @Override protected void onStop() { super.onStop(); unregisterReceiver(connectivityReceiver); } } // ConnectivityReceiver.java public 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 connectivity status if (isConnected) { // Connected to the internet } else { // Not connected to the internet } } }

Keywords: Android Broadcast Receiver connectivity changes Android components integration