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.
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
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?