"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Handle Internet Connectivity Changes in Android?

How to Handle Internet Connectivity Changes in Android?

Published on 2024-11-07
Browse:364

How to Handle Internet Connectivity Changes in Android?

Handling Internet Connectivity Changes in Android

The question centers on the need for a Broadcast Receiver that can monitor changes in internet connectivity, as the existing code only detects connectivity changes.

To address this, here's an alternative approach:

public class NetworkUtil {
    public static final int TYPE_WIFI = 1;
    public static final int TYPE_MOBILE = 2;
    public static final int TYPE_NOT_CONNECTED = 0;

    public static int getConnectivityStatus(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (activeNetwork != null) {
            if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                return TYPE_WIFI;

            if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                return TYPE_MOBILE;
        }
        return TYPE_NOT_CONNECTED;
    }
}

This method determines if the device is connected to WiFi or mobile data.

public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {
        int status = NetworkUtil.getConnectivityStatus(context);
        if ("android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction()) {
            if (status == NetworkUtil.TYPE_NOT_CONNECTED) {
                // Handle loss of internet connectivity
            } else {
                // Handle restoration of internet connectivity
            }
        }
    }
}

This BroadcastReceiver monitors connectivity state changes and triggers actions based on the current status. Remember to include the appropriate permissions and register the receiver in your AndroidManifest.xml:

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3