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?
Asked
Active
Viewed 1,036 times
1
-
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 Answers
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

Iggy Van Der Wielen
- 124
- 6
-
-
1no then you will have to look into the http://developer.android.com/reference/android/net/ConnectivityManager.html – Iggy Van Der Wielen Dec 23 '11 at 11:55
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