Android 互联网连接检查问题
我是 Android 开发新手,正在开发一个 Android 应用程序,该应用程序需要手机通过 Wifi、EDGE 或 3G 连接到互联网。
这是我用来检查互联网连接是否可用的代码
public static boolean isConnected()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
我还在清单文件中设置了这些权限
<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 也会发生同样的情况。
希望有人知道这个问题的解决方案。
提前致谢!
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" />
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.
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果崩溃直接发生在您的线路上:
那么这意味着
getActiveNetworkInfo()
返回null
,因为没有活动网络 - 在这种情况下,您的isConnected()
方法应返回false
。If the crash is directly on your line:
then that means
getActiveNetworkInfo()
returnednull
, because there is no active network -- in that case, yourisConnected()
method should returnfalse
.我写了这个方法来处理这个问题:
我想这是一种方法......
I wrote this method to handle this:
One way to do it I guess...
要检查互联网是否存在,只能在设备上检查......在模拟器上它可能不起作用......我有以下代码&它在 Android 设备上 100% 工作......:)
}
To check internet is there or not can be checked only on device......On emulator it may not work.... I have got the following code & its working 100% on android device..... :)
}
您已经使用了这个片段。
You have used this snippet.
使用它来确定是否连接到 wifi/3g:
并使用它自己启用 wifi:
use this to detemine if connceted to wifi/3g:
and this to enable wifi yourself: