繁体   English   中英

Android - 检查设备是否已连接到互联网

[英]Android - checking if the device is connected to the internet

有没有简单的方法,如何检查设备是否主动连接到互联网(=通过GPRS,EDGE,UMTS,HSDPA或Wi-Fi连接)?

谢谢

是的,我使用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;
            }
        }
    }
}

我在我的一个应用程序中使用它:

private boolean isOnline()  {
    ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    return (ni != null && ni.isConnected());
}

您将在清单文件中需要这些权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

您可以尝试撤消本地IP地址以检查设备是否已连接到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();
            }
        }
    }

返回iNetAddress.getHostAddress()。toString(); 会给你IP地址。 您需要添加权限

<uses-permission android:name="android.permission.INTERNET" />

注意:如果您在仿真器中工作,它将重新调整仿真器IP(通常为10.0.2.15)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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