-1

Possible Duplicate:
Checking internet connection on android

In my application I want to check internet connection. If the device is not connected to internet I want to close my app. So I use this method for checking the internet connection.

public boolean isDeviceConnectedToInternet() {
        ConnectivityManager cm =
            (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }

User permissions are set:

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

I turned off my wifi and running the app , I got true in Log cat.

While running in my Android device it's working. But I can't figure out why the same thing is not happening in my emulator.

Community
  • 1
  • 1
Sridhar
  • 2,228
  • 10
  • 48
  • 79

2 Answers2

2
 public void checkConnection() throws NoInternetException {
    boolean connected = false;

    ConnectivityManager cm = 
            (ConnectivityManager) 
            context.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (cm != null) {
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();

        for (NetworkInfo ni : netInfo) {
            if ( ni.isConnected() && ni.isAvailable() ) {
                connected = true;
            }
        }
    }
    if (! connected) {
        throw new NoInternetException("NO INTERNET CONNECTION");
    }
}

Here I'm throwing exception, if there is no network. Anyway you can return varuable connected

JunR
  • 202
  • 1
  • 6
1

A Simple Code for Checking Internet Connection.

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();

String status = netInfo.getState().toString();
if (status.equals("CONNECTED")) 
{
    //DO you work or return your flag
} 
else 
{
    Log.e("error", "No connection available ");
}
Chirag
  • 56,621
  • 29
  • 151
  • 198
  • I turned off my wifi connection and run the app still i got true in Logcat. I have a webview in my app, here web page not available window opens – – Sridhar Oct 01 '12 at 07:04