Alex Rivera | Logout

Detect whether there is an Internet connection available on Android

Asked 2010-11-21T16:35:05.273
749

Possible Duplicate:
How to check internet access on Android? InetAddress never timeouts

I need to detect whether the Android device is connected to the Internet.

The NetworkInfo class provides a non-static method isAvailable() that sounds perfect.

Problem is that:

NetworkInfo ni = new NetworkInfo();
if (!ni.isAvailable()) {
    // do something
}

throws this error:

The constructor NetworkInfo is not visible.

Safe bet is there is another class that returns a NetworkInfo object. But I don't know which.

  1. How to get the above snippet of code to work?
  2. How could I have found myself the information I needed in the online documentation?
  3. Can you suggest a better way for this type of detection?
Edit
Report

1 Answer

80

Step 1: Create a class AppStatus in your project(you can give any other name also). Then please paste the given below lines into your code:

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;


public class AppStatus {

    static Context context;

    public static AppStatus getInstance(Context ctx) {
        context = ctx.getApplicationContext();
        return new AppStatus();
    }

    public boolean isOnline() {
        try {
            ConnectivityManager cm = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isAvailable() &&
                networkInfo.isConnected();
       
        } catch (Exception e) {              
            Log.v("CheckConnectivity ", e.toString());
        }
        return false;
    }
}

Step 2: Now to check if the your device has network connectivity then just add this code snippet where ever you want to check ...

if (AppStatus.getInstance(this).isOnline()) {

    Toast.makeText(this,"You are online!!!!",8000).show();

} else {

    Toast.makeText(this,"You are not online!!!!",8000).show();
    Log.v("Home", "############################You are not online!!!!");    
}
answered 2011-08-08T19:30:07.237

Your Answer