我怎么知道是否我的设备连接网络或不?如何检测连接?任何样品code?
How would i know whether my device is connected the web or not? How can i detect connectivity? Any sample code?
推荐答案
首先,你需要的权限知道设备是否连接到网络,或不。这需要在您的清单,在<舱单>
元素:
First, you need permission to know whether the device is connected to the web or not. This needs to be in your manifest, in the <manifest>
element:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
接下来,你需要获得一个引用ConnectivityManager:
ConnectivityManager cm = (ConnectivityManager) Context.getSystemService(Context.CONNECTIVITY_SERVICE);
从那里,你需要获得一个的NetworkInfo 的对象。对于大多数人来说,这将意味着使用ConnectivityManager. getActiveNetworkInfo():
From there you need to obtain a NetworkInfo object. For most, this will mean using ConnectivityManager. getActiveNetworkInfo():
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
return false;
}
从那里,你只需要使用的NetworkInfo的方法之一,以确定该设备连接到互联网:
From there, you just need to use one of NetworkInfo's methods to determine if the device is connected to the internet:
boolean isConnected = ni.isConnected();
相关推荐
最新文章