Reputation: 17783
is there any simple way, how to check if the device is actively connected into internet (= is connected via GPRS, EDGE, UMTS, HSDPA or Wi-Fi)?
Thanks
Upvotes: 2
Views: 4273
Reputation: 436
I use this in one of my apps:
private boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return (ni != null && ni.isConnected());
}
You will need these permissions in your Manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Upvotes: 3
Reputation: 2393
You can try retreaving the Local IP address to check whether device is connected to Internet.
for (Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces(); enumeration.hasMoreElements();) {
NetworkInterface networkInterface = enumeration.nextElement();
for (Enumeration<InetAddress> enumIpAddress = networkInterface.getInetAddresses(); enumIpAddress.hasMoreElements();) {
InetAddress iNetAddress = enumIpAddress.nextElement();
if (!iNetAddress.isLoopbackAddress()) {
return iNetAddress.getHostAddress().toString();
}
}
}
The return iNetAddress.getHostAddress().toString(); will give you the IP address. You need to add permission
<uses-permission android:name="android.permission.INTERNET" />
Note: If you are working in Emulator it will retun the emulator IP (generally it will be 10.0.2.15)
Upvotes: 1
Reputation: 17216
Yes, I use isReachable.
public class Extras {
public static class Internet {
public static boolean isOnline() {
try {
InetAddress.getByName("google.ca").isReachable(3);
return true;
} catch (UnknownHostException e){
return false;
} catch (IOException e){
return false;
}
}
}
}
Upvotes: 6