Android 互联网连接检查问题 [英] Android internet connectivity check problem

查看:45
本文介绍了Android 互联网连接检查问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Android 开发新手,正在开发一个 Android 应用程序,该应用程序要求手机通过 Wifi、EDGE 或 3G 连接到互联网.

I'm new to Android development and working on an Android application that requires the phone to be connected to the internet, through either Wifi, EDGE or 3G.

这是我用来检查互联网连接是否可用的代码

This is the code that I'm using to check whether an internet connection is available

public static boolean isConnected()
{
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    return cm.getActiveNetworkInfo().isConnectedOrConnecting();
}

我也在清单文件中设置了这些权限

I've also set these permissions in the manifest file

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

当启用 3G 时,这在运行 Android 1.5 版的模拟器中运行良好,但是当我禁用 3G 连接时它会崩溃.当我调用 isConnectedOrConnecting() 时,我的应用程序抛出空指针异常.同样的事情也发生在我运行 Android 2.1 的 HTC Desire 上.

This works fine in the emulator running version 1.5 of Android when 3G is enabled, but it crashes when I disable the 3G connection. My application throws a null pointer exception when I call isConnectedOrConnecting(). The same thing also happens on my HTC Desire running Android 2.1.

希望任何人都知道解决方案.

Hope that anyone knows the solution to this.

提前致谢!

推荐答案

如果崩溃直接在您的线路上:

If the crash is directly on your line:

return cm.getActiveNetworkInfo().isConnectedOrConnecting();

那么这意味着 getActiveNetworkInfo() 返回了 null,因为没有活动网络——在这种情况下,你的 isConnected() 方法应该返回 false.

then that means getActiveNetworkInfo() returned null, because there is no active network -- in that case, your isConnected() method should return false.

这篇关于Android 互联网连接检查问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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