开发者

Android - checking if the device is connected to the internet

is there any simple way, how to check if the device is actively connected into internet (= is connected via GPRS, 开发者_JS百科EDGE, UMTS, HSDPA or Wi-Fi)?

Thanks


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;
            }
        }
    }
}


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" />


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜