Android Development
Broadcast Receiver
Internet Connectivity
Mobile Apps
Android Apps

Broadcast receiver for checking internet connection in android app

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In Android development, maintaining an awareness of network connectivity status is crucial for apps that rely on internet availability. A common approach to managing network changes effectively is to implement a broadcast receiver specifically designed for monitoring internet connectivity.

Understanding Broadcast Receivers

A Broadcast Receiver in Android is an application component that responds to system-wide broadcast announcements. Many broadcasts originate from the system—for instance, announcements that the timezone has changed, or that the device battery is low. Apps can also initiate broadcasts—for example, to let other apps know that some data has been downloaded to the device and is available for them to use.

Use Case: Monitoring Network Connectivity

For applications that depend on network availability to operate properly, monitoring connectivity can significantly enhance user experience. By recognizing changes in network state, an app can react appropriately—by notifying the user, delaying network operations, or executing an alternative plan.

Implementing a Broadcast Receiver for Internet Connectivity

Here's how you can create a broadcast receiver that listens for changes in network status:

Permissions

First, you must include the necessary permissions in your AndroidManifest.xml:

xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

This permission allows the app to access information about network connectivity states.

Defining the Receiver

Next, define the receiver in the manifest file:

xml
1<receiver android:name=".NetworkChangeReceiver">
2    <intent-filter>
3        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
4    </intent-filter>
5</receiver>

This snippet defines a receiver class NetworkChangeReceiver which will be triggered on any connectivity change.

The Receiver Class

In the NetworkChangeReceiver class, override the onReceive() method, which handles the broadcast:

java
1public class NetworkChangeReceiver extends BroadcastReceiver {
2    @Override
3    public void onReceive(Context context, Intent intent) {
4        ConnectivityManager connectivityManager = 
5                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
6        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
7        boolean isConnected = networkInfo != null && networkInfo.isConnected();
8
9        if (isConnected) {
10            Toast.makeText(context, "Internet Connected", Toast.LENGTH_LONG).show();
11        } else {
12            Toast.makeText(context, "Internet Connection Lost", Toast.LENGTH_LONG).show();
13        }
14    }
15}

This method checks if the device is connected to the internet and displays the appropriate message.

Android API Changes

From Android N (API 24) onward, receiving broadcasts for CONNECTIVITY_ACTION became deprecated for apps targeting API level 24 and higher. For these cases, it is recommended to use ConnectivityManager.NetworkCallback for listening to network changes.

Best Practices and Enhancements

  1. Using NetworkCallback for New Apps: For new applications or ones targeting recent API levels, employ NetworkCallback instead of broadcasting receivers for more efficiency and reliability.
  2. Optimization: Reduce the use of background services for checking network state. Instead, consider checking connectivity when your app is active or about to perform network operations.
  3. User Experience: Design your app to gracefully handle the absence of network connection. Offer offline functionality or cached content when possible.

Summary Table

AspectDetails
Component UsedBroadcast Receiver, ConnectivityManager.NetworkCallback
Permissions RequiredACCESS_NETWORK_STATE
API Level ConsiderationsCONNECTIVITY_ACTION deprecated in API level 24+
Best PracticeUse NetworkCallback for applications targeting API level 24 and above
User ExperienceHandle no connectivity gracefully; offer offline modes or caching

Conclusion

Monitoring internet connectivity in an Android app can significantly influence the user experience and operational efficiency. Choose the right approach based on the app's target API level and intended user base to ensure responsiveness and robust performance.


Course illustration
Course illustration

All Rights Reserved.