android - 如何检查android中的互联网连接?

标签 android

friend ,

我正在尝试检查 android 中的互联网连接并使用以下代码

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 连接,它会给我 true,如果未连接 internet,它也会给我 true。

有人指导我解决方案是什么吗?

最佳答案

if 子句中的逻辑可能存在一些问题。

我用这个:

/**
 * 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;
}

关于android - 如何检查android中的互联网连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3211978/

相关文章:

Android - 指示菜单可用

android - 将图像的字节数组保存到文件

java - 我怎样才能使杰里米范斯坦的滑动菜单的后 View 可点击

android - 在 Imageview 的每个触摸坐标上绘制图像

java - Unity3D - 构建播放器时出错 : Win32Exception:

android - 将纯文本作为 POST 正文发送会导致改造出现问题

java - Sinch 调用按钮错误?

java - 如何修复 "Failed to notify build listener"错误?

android - 使用 Maven 进行 Android 集成测试中的 NoSuchFieldError

java - android中的指数函数