简体   繁体   中英

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, 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM