如何检查网络连接在机器人? [英] How to check internet connectivity in android?

查看:96
本文介绍了如何检查网络连接在机器人?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

朋友,

我试图检查internetconnectivity在Android和使用以下code

i am trying to check internetconnectivity in android and using following code

final ConnectivityManager conn_manager = (ConnectivityManager) 
            this.getSystemService(Context.CONNECTIVITY_SERVICE);


            final NetworkInfo network_info = conn_manager.getActiveNetworkInfo();
            if ( network_info != null && network_info.isConnected() ) 
            {
                return true;
            }
            else
            {
                return false;
            }

但它给我的网络/ WiFi连接,如果WiFi是连接它给了我真正的,如果没有连接互联网,然后它也给了我正确的。

but it gives me network/ wifi connectivity if wifi is connected it gives me true and if internet is not connected then it also gives me true.

任何一个指导我该如何解决?

any one guide me what is the solution?

推荐答案

也许有些问题你有如果子句中存在的逻辑。

Probably some issue with the logic you have in the if clause there.

我用这样的:

/**
 * Checks if we have a valid Internet Connection on the device.
 * @param ctx
 * @return True if device has internet
 *
 * Code from: http://www.androidsnippets.org/snippets/131/
 */
public static boolean haveInternet(Context ctx) {

    NetworkInfo info = (NetworkInfo) ((ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

    if (info == null || !info.isConnected()) {
        return false;
    }
    if (info.isRoaming()) {
        // here is the roaming option you can change it if you want to
        // disable internet while roaming, just return false
        return false;
    }
    return true;
}

这篇关于如何检查网络连接在机器人?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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