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

Android-检查设备是否连接到互联网,android,Android,有没有简单的方法,如何检查设备是否主动连接到internet(=通过GPRS、EDGE、UMTS、HSDPA或Wi-Fi连接) 谢谢是的,我使用isReachable public class Extras { public static class Internet { public static boolean isOnline() { try { InetAddress.getByName("google.ca

有没有简单的方法,如何检查设备是否主动连接到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;
            }
        }
    }
}

您可以尝试重新获取本地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();
            }
        }
    }
for(枚举枚举=NetworkInterface.getNetworkInterfaces();枚举.hasMoreElements();){
NetworkInterface NetworkInterface=enumeration.nextElement();
对于(枚举Enumeration enumIpAddress=networkInterface.getInetAddresses();enumIpAddress.hasMoreElements();){
InetAddress InetAddress=enumIpAddress.nextElement();
如果(!iNetAddress.isLoopbackAddress()){
返回iNetAddress.getHostAddress().toString();
}
}
}
返回iNetAddress.getHostAddress().toString();我会给你IP地址。您需要添加权限

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


注意:如果您在Emulator中工作,它将重新运行Emulator IP(通常为10.0.2.15)

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

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


谢谢,但我的情况是,我得到了一些有关GPS的信息,当GSM连接中断时,我得到了坏消息。我只能将其添加到while(1)循环中,并不断检查是否可以访问internet目标,这可能会“吃掉”我的FUP数据限制。我想知道是否有一些内部检查,比如,互联网连接是否可以访问,做些什么,如果没有,则不执行任何操作如果您连接到Wifi网络,这仍然会为您提供本地IP,但您的Wifi路由器可能没有连接到internet。如果存在网络连接,或如果该网络连接到internet,则返回该值吗?ForceMagic的意思是,如果您的设备连接到没有网络的路由器,则返回false连接,或者如果您的设备已连接到capative network或real network