如何检查是否一个Android设备连接到网络? [英] How can i check whether an android device is connected to the web?
问题描述
我怎么知道是否我的设备连接网络或不?如何检测连接?任何样品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" />
接下来,你需要获得一个引用<一个href="http://developer.android.com/intl/fr/reference/android/net/ConnectivityManager.html">ConnectivityManager:
ConnectivityManager cm = (ConnectivityManager) Context.getSystemService(Context.CONNECTIVITY_SERVICE);
从那里,你需要获得一个的NetworkInfo 的对象。对于大多数人来说,这将意味着使用<一个href="http://developer.android.com/intl/fr/reference/android/net/ConnectivityManager.html#getActiveNetworkInfo%28%29">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();
这篇关于如何检查是否一个Android设备连接到网络?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!