Question

I used following code for checking internet connection.

 public static boolean checkNetworkConnection(Context context) {
        boolean connected = true;
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
                .getState() == android.net.NetworkInfo.State.CONNECTED
                || connectivityManager.getNetworkInfo(
                        ConnectivityManager.TYPE_WIFI).getState() == android.net.NetworkInfo.State.CONNECTED) {
            connected = true;
        } else
            connected = false;
}

This code is working fine in below mobile. But it is not working in Google nexus 7 (android 4.2).

When I test this code in Google nexus 7 (android 4.2). I got error.

Null pointer exception in connection manager

Was it helpful?

Solution

For me it work:

public static boolean isInternetEnabled() {
    ConnectivityManager conMgr = (ConnectivityManager) YourApp.context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting())
        return true;
    else
        return false;
}

OTHER TIPS

You will need this permission in your manifest:

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

Check TYPE_MOBILE is null or not using below code.

connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top