Android判断网络连接

来源:互联网 发布:广州谷得网络 编辑:程序博客网 时间:2024/05/22 06:13
package com.ior.service;


import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;


/** 检查联网状态 */
public class CheckNetworkState {
/** wifi联网? */
public static boolean isWifi(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkINfo = cm.getActiveNetworkInfo();
if (networkINfo != null
&& networkINfo.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
}
return false;
}


/**3G联网? */
public static boolean is3G(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkINfo = cm.getActiveNetworkInfo();
if (networkINfo != null
&& networkINfo.getType() == ConnectivityManager.TYPE_MOBILE) {
return true;
}
return false;
}


/** WIFI打开? */
public static boolean isWifiEnabled(Context context) {
ConnectivityManager mgrConn = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
TelephonyManager mgrTel = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
return ((mgrConn.getActiveNetworkInfo() != null && mgrConn
.getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED) || mgrTel
.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS);
}


/** 已连网络? */
public static boolean isNetworkAvailable(Context context) {
try {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager
.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
} catch (Exception e) {
return false;
}
}
}
0 0