android - 如何在 Google nexus 7 (android 4.2) 中检查互联网连接

标签 android nullpointerexception network-connection

我使用以下代码来检查互联网连接。

 public static boolean checkNetworkConnection(Context context) {
        boolean connected = true;
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
                .getState() == android.net.NetworkInfo.State.CONNECTED
                || connectivityManager.getNetworkInfo(
                        ConnectivityManager.TYPE_WIFI).getState() == android.net.NetworkInfo.State.CONNECTED) {
            connected = true;
        } else
            connected = false;
}

此代码在以下移动设备中运行良好。但它不适用于 Google nexus 7 (android 4.2)。

当我在 Google nexus 7 (android 4.2) 中测试此代码时。我有错误。

连接管理器中的空指针异常

最佳答案

对我来说它有效:

public static boolean isInternetEnabled() {
    ConnectivityManager conMgr = (ConnectivityManager) YourApp.context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting())
        return true;
    else
        return false;
}

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

相关文章:

android - 如何禁用谷歌地图重新对齐北按钮

java - jUnit单元测试空指针异常而不是自定义异常

Spring 数据 JPA。 Repositories 继承,抛出 BeanCreationException,NullPointerException

ios - 在 PhoneGap 应用程序中检查互联网连接

android - SD卡图像的相对路径

android - SELinux - 是否可以从域继承?

java - 如何获取十六进制调色板

java - 什么是NullPointerException,我该如何解决?

ios - iOS 模拟器上没有网络连接,但只有我的应用程序

javascript - Chrome 操作系统,通过 Chrome 扩展程序快速判断是否有互联网连接?