Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android internet connectivity check problem

I'm new to Android development and working on an Android application that requires the phone to be connected to the internet, through either Wifi, EDGE or 3G.

This is the code that I'm using to check whether an internet connection is available

public static boolean isConnected()
{
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    return cm.getActiveNetworkInfo().isConnectedOrConnecting();
}

I've also set these permissions in the manifest file

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

This works fine in the emulator running version 1.5 of Android when 3G is enabled, but it crashes when I disable the 3G connection. My application throws a null pointer exception when I call isConnectedOrConnecting(). The same thing also happens on my HTC Desire running Android 2.1.

Hope that anyone knows the solution to this.

Thanks in advance!

like image 878
Charles Avatar asked May 02 '10 12:05

Charles


People also ask

How does Android verify Internet connectivity?

Android devices detect captive portals requesting a specific URL, that currently is http://connectivitycheck.gstatic.com/generate_204. If they receive a 204 response then there's connectivity. If they receive a 30x response, then there's a captive portal in the way.

Why is my phone connected but no Internet?

Issues with the Router A common reason why your phone has a WiFi connection but no Internet access is that there is a technical issue with your router. If your router is experiencing any kind of bugs or problems, that affects how your devices including your Android devices connect to the Internet.


2 Answers

If the crash is directly on your line:

return cm.getActiveNetworkInfo().isConnectedOrConnecting();

then that means getActiveNetworkInfo() returned null, because there is no active network -- in that case, your isConnected() method should return false.

like image 152
CommonsWare Avatar answered Oct 12 '22 00:10

CommonsWare


I wrote this method to handle this:

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    if (ni!=null && ni.isAvailable() && ni.isConnected()) {
        return true;
    } else {
        return false; 
    }
}

One way to do it I guess...

like image 32
mutable2112 Avatar answered Oct 12 '22 00:10

mutable2112