码迷,mamicode.com
首页 > 移动开发 > 详细

判断 Android 手机是否处于联网状态

时间:2015-07-30 16:30:28      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

Android App的开发大多数情况下都要与网络进行连接,那如何判断网络是否连接,处于何种连接呢?下面是关于连接写的一个方法,可以根据需求做相应的修改:

private String connection(Context context) {
//判断联网,一定要记得写权限<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
String connectInfo = "网络未连接";
ConnectivityManager connect = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connect.getActiveNetworkInfo();
if(info != null && info.isConnected()){
//if(info.isAvailable()){//此判断在使用时会有异常,需要处理
connectInfo = "网络已经连接,";

//GPS是否打开
if(isGpsEnabled(this)){
connectInfo += "GPS已经开启";
}else {
connectInfo += "GPS未开启";
}

//WiFi是否打开
if(isWifiEnabled(this,connect)){
connectInfo += "WIFI开启";
}else {
connectInfo += "WIFI未开启";
}

int netType = info.getType();
if(netType == ConnectivityManager.TYPE_WIFI){
connectInfo += "\n当前使用WIFI";
}else if(netType == ConnectivityManager.TYPE_MOBILE){
connectInfo += "\n当前使用移动连接";
}else {
connectInfo += "\n当前使用连接是:"+netType;
}
}
return connectInfo;
}

//判断GPS是否打开
public static boolean isGpsEnabled(Context context) {
LocationManager lm = ((LocationManager) context
.getSystemService(Context.LOCATION_SERVICE));
List<String> accessibleProviders = lm.getProviders(true);
return accessibleProviders != null && accessibleProviders.size() > 0;
}
//判断WIFI是否打开
public static boolean isWifiEnabled(Context context,ConnectivityManager mgrConn) {
TelephonyManager mgrTel = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
return ((mgrConn.getActiveNetworkInfo() != null && mgrConn
.getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED) || mgrTel
.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS);
}

 

判断 Android 手机是否处于联网状态

标签:

原文地址:http://www.cnblogs.com/hais/p/4689540.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!