1

My requirement is that a piece of code should be triggered immediately whenever internet connection gets unavailable. Is there a way to do it in android?

Sush
  • 6,839
  • 1
  • 18
  • 26
  • yes its possible, what you have tried so far to check internet connection. – Paresh Mayani Dec 23 '11 at 10:48
  • ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); if (ni!=null && ni.isAvailable() && ni.isConnected()) { return true; } else { return false; } – Sush Dec 23 '11 at 11:05

3 Answers3

2

You need to use BroadCastReceiver see the following link

Checking the Networking Connectivity using BroadcastReceiver in Android

Community
  • 1
  • 1
Sunil Kumar Sahoo
  • 53,011
  • 55
  • 178
  • 243
1

Look into the android SDK. http://developer.android.com/reference/android/telephony/PhoneStateListener.html you can use the PhoneState listener to look for data connection state changes

1

Try this:

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

the function will return false if there is no internet or working data connection ....

Rishi
  • 44
  • 2