即使互联网是不可用的Andr​​oid的NetworkInfo总是返回true [英] Android networkinfo always returns true even if internet is not available

查看:240
本文介绍了即使互联网是不可用的Andr​​oid的NetworkInfo总是返回true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这code总是返回true。当登录按钮pssed $ P $调用此方法。我第一次尝试用连接(在模拟器)的WiFi。它返回true,然后我断开无线网络,然后试图。它仍然返回true。

 公共静态布尔isNetworkAvailable(上下文的背景下){    ConnectivityManager厘米=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
            的NetworkInfo NETWORKINFO = cm.getActiveNetworkInfo();
            //如果没有网络可用NETWORKINFO将为空
            //否则检查,如果我们连接
            如果(NETWORKINFO = NULL&放大器;!&安培; networkInfo.isConnected()){
                 国家网络= networkInfo.getState();
                 Log.d(这里,真);
                 回报(网络== || NetworkInfo.State.CONNECTED网络== NetworkInfo.State.CONNECTING);            }
            Log.d(here1,假);
            返回false;
}


解决方案

这code ++工程,设备上的,因为我用我的应用程序之一非常类似的东西。请记住,这code会告诉你,无论你是的连接,以一个网络,而不是网络是否你连接到具有Internet连接。如果你使用模拟器,它总是通过3G模拟连接,因此断开电脑的WiFi不会改变。你可以把模拟器在飞行模式下,这应该给你的假,你所期待的。

我已经在我的应用程序做的是创造接收网络更改广播的服务。一旦网络连接后,就会试图下载一个已知的(小)的文件在互联网上。仅如果成功将其再播互联网可用意图所有在此基础上的活动,则可以改变状态。

This code always returns true. This gets called when a Login button is pressed. I first tried with wifi connected (on emulator). It returned true and then I disconnected wifi and then tried. it still returns true.

public static boolean isNetworkAvailable( Context context) {

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            // if no network is available networkInfo will be null
            // otherwise check if we are connected
            if (networkInfo != null && networkInfo.isConnected()) {
                 State network = networkInfo.getState();
                 Log.d("here", "true");
                 return (network == NetworkInfo.State.CONNECTED || network == NetworkInfo.State.CONNECTING);

            }
            Log.d("here1", "false");
            return false;
}

解决方案

This code works on-device, as I'm using something very similar in one of my apps. Keep in mind that this code will tell you whether you are connected to a network, not whether the network you are connected to has internet connectivity. If you're using the emulator, it's always connected via 3G simulation, so disconnecting your computer's wifi won't change that. You could put the emulator in airplane mode, which should give you the "false" you were looking for.

What I've done in my apps is to create a service which receives network change broadcasts. Once a network is connected, it then tries to download a known (small) file over the internet. Only if that succeeds will it then broadcast an internet-available intent to all the activities, which can then change state based on this.

这篇关于即使互联网是不可用的Andr​​oid的NetworkInfo总是返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆