判断Android手机是否联网
文章分类:移动开发
android 中查看当前是否联网
方法如下:
ConnectivityManager cManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cwjManager.getActiveNetworkInfo();
if (info != null && info.isAvailable()){
//do something
//能联网
return true;
}else{
//do something
//不能联网
return false;
}
如果为True则表示当前Android手机已经联网,可能是WiFi或GPRS、HSDPA等等,具体的可以通过 ConnectivityManager 类的getActiveNetworkInfo() 方法判断详细的接入方式。
同时要在manifest里面加个权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
文档如下:
boolean android.net.NetworkInfo.isAvailable()
public boolean isAvailable ()
Indicates whether network connectivity is possible. A network is unavailable when a persistent or semi-persistent condition prevents the possibility of connecting to that network. Examples include
The device is out of the coverage area for any network of this type.
The device is on a network other than the home network (i.e., roaming), and data roaming has been disabled.
The device's radio is turned off, e.g., because airplane mode is enabled.
Returns
true if the network is available, false otherwise
方法如下:
ConnectivityManager cManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cwjManager.getActiveNetworkInfo();
if (info != null && info.isAvailable()){
//do something
//能联网
return true;
}else{
//do something
//不能联网
return false;
}
如果为True则表示当前Android手机已经联网,可能是WiFi或GPRS、HSDPA等等,具体的可以通过 ConnectivityManager 类的getActiveNetworkInfo() 方法判断详细的接入方式。
同时要在manifest里面加个权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
文档如下:
boolean android.net.NetworkInfo.isAvailable()
public boolean isAvailable ()
Indicates whether network connectivity is possible. A network is unavailable when a persistent or semi-persistent condition prevents the possibility of connecting to that network. Examples include
The device is out of the coverage area for any network of this type.
The device is on a network other than the home network (i.e., roaming), and data roaming has been disabled.
The device's radio is turned off, e.g., because airplane mode is enabled.
Returns
true if the network is available, false otherwise
本文介绍了一种简单的方法来检查Android设备是否已连接到互联网。通过使用ConnectivityManager类和getActiveNetworkInfo()方法,开发者可以轻松地确定设备是否处于在线状态,并获取具体的连接类型。
272

被折叠的 条评论
为什么被折叠?



