Android的互联网连接检查问题互联网、问题、Android

2023-09-12 21:38:18 作者:刚好遇见你

我是新来的Andr​​oid的发展和工作的一个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.

这是我使用来检查网络连接是否可用code

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()我的应用程序会引发空指针异常。同样的事情也发生在我的HTC Desire运行Android 2.1。

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.

在此先感谢!

推荐答案

如果飞机坠毁的直接在行:

return cm.getActiveNetworkInfo().isConnectedOrConnecting();

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

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