问题描述
我需要检测是否在Android设备连接到互联网。
在的NetworkInfo
类提供了一个非静态方法 isAvailable()
这听起来很完美。
问题是:
的NetworkInfo NI =新的NetworkInfo();
如果(!ni.isAvailable()){
// 做一点事
}
抛出这个错误:
构造函数的NetworkInfo是不可见的。
安全的办法是有另一个类返回的NetworkInfo
对象。但我不知道是哪个。
- 如何获得code上面的代码工作?
- 我怎么能找到我自己,我需要在联机文档中的信息?
- 您能否提供这种类型检测的一个更好的办法?
ConnectivityManager的
返回 getActiveNetworkInfo()
方法的NetworkInfo
实例重新presenting第一个连接的网络接口,它可以找到或者空
如果没有的接口相连。检查,如果该方法返回空
应该足以告诉我们,如果一个互联网连接是否可用。
私人布尔isNetworkAvailable(){
ConnectivityManager connectivityManager
=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
的NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
返回activeNetworkInfo = NULL和放大器;!&安培; activeNetworkInfo.isConnected();
}
您还需要:
<使用-权限的Android:名称=android.permission.ACCESS_NETWORK_STATE/>
在你的Android清单。
编辑:
请注意,拥有积极的网络接口并不能保证一个特定的网络服务。网络问题,服务器宕机,低信号,圈养门户网站,内容过滤器之类的都可以$ P $到达服务器pvent您的应用程序。例如,你不能告诉是肯定的,如果您的应用程序可以达到微博,直到收到来自Twitter的服务,有效的响应。
I need to detect whether the Android device is connected to the Internet.
The NetworkInfo
class provides a non-static method isAvailable()
that sounds perfect.
Problem is that:
NetworkInfo ni = new NetworkInfo();
if (!ni.isAvailable()) {
// do something
}
throws this error:
The constructor NetworkInfo is not visible.
Safe bet is there is another class that returns a NetworkInfo
object. But I don't know which.
- How to get the above snippet of code to work?
- How could I have found myself the information I needed in the online documentation?
- Can you suggest a better way for this type of detection?
The getActiveNetworkInfo()
method of ConnectivityManager
returns a NetworkInfo
instance representing the first connected network interface it can find or null
if none of the interfaces are connected. Checking if this method returns null
should be enough to tell if an internet connection is available or not.
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
You will also need:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
in your android manifest.
Edit:
Note that having an active network interface doesn't guarantee that a particular networked service is available. Network issues, server downtime, low signal, captive portals, content filters and the like can all prevent your app from reaching a server. For instance you can't tell for sure if your app can reach Twitter until you receive a valid response from the Twitter service.
这篇关于检测是否有在Android上提供互联网连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!