即使数据流量处于活动状态,ConnectivityManager getActiveNetworkInfo() 也始终为 null
我正在开发一个 Android 项目,我需要检查互联网连接。我在网上搜索了一下,在 stackoverflow 上找到了解决方案。但是,我在检查互联网状态时遇到问题。我已经到处搜索,但找不到任何解决我的问题的方法。
这是清单:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
这是检查互联网是否已连接的代码:
cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo ni = cm.getActiveNetworkInfo();
isConnected = (ni != null && ni.isAvailable() && ni.isConnected()) ? true : false;
}
问题是,即使 TYPE_MOBILE 数据流量处于活动状态,ni 变量也始终为空。访问运营商的互联网流量这是测试的正确方法吗?或者我必须使用 TelephonyManager? 这很奇怪,因为我使用了 getNetworkInfo()[] 并对其进行了调试,TYPE_MOBILE 的 HSPA 出现在那里,但 isAvalaible 始终为 false 并且 getState() = DISCONNECTED。但是,我启用了运营商的数据流量并正在工作(在其他应用程序中)
[编辑]:顺便说一句,我直接在设备中而不是在模拟器中测试它:)。
提前致谢。问候。
i'm working on a android project and i had the need to check for internet connection. i searched the web and i found a solution here on stackoverflow. However, i'm having problems on checking the internet state. I already searched everywhere but i can't find any solution for my problem.
Here is the manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Here is the code for checking if internet is connected:
cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo ni = cm.getActiveNetworkInfo();
isConnected = (ni != null && ni.isAvailable() && ni.isConnected()) ? true : false;
}
The problem is that even with TYPE_MOBILE data traffic active the ni variable is always null. To access the operators internet traffic is this the correct way of testing it? Or i have to use TelephonyManager?
It's wierd because i used getNetworkInfo()[] and debugged it, the HSPA for TYPE_MOBILE appears there but isAvalaible is always false and getState() = DISCONNECTED. However i have operator's data traffic enabled and working (in other applications)
[EDIT]: by the way im testing it directly in the device not in emulator :).
Thanks in advance. Regards.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ConnectivityManager
中存在各种错误。请参阅 http://code.google.com/p/android/issues/detail?id=11866 和 http://code.google.com/p/android/issues/detail?id=11891 例如。
There are various bugs in
ConnectivityManager
.See http://code.google.com/p/android/issues/detail?id=11866 and http://code.google.com/p/android/issues/detail?id=11891 for example.