网络连接判断
android网络编程时常需要用到连接判断:
/**
* 判断Android客户端网络是否连接
* @param context
* @return 真假
*/public static boolean checkNet(Context context) {
try {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
if (info.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
} catch (Exception e) {
return false;
}
return false;
}
判断网络连接
* 检验网络连接 并toast提示
*
* @return
*/
public boolean note_Intent(Context context) {
ConnectivityManager con = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkinfo = con.getActiveNetworkInfo();
if (networkinfo == null || !networkinfo.isAvailable()) {
// 当前网络不可用
Toast.makeText(context.getApplicationContext(), "请先连接Internet!",
Toast.LENGTH_SHORT).show();
return false;
}
boolean wifi = con.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.isConnectedOrConnecting();
if (!wifi) { // 提示使用wifi
Toast.makeText(context.getApplicationContext(), "建议您使用WIFI以减少流量!",
Toast.LENGTH_SHORT).show();
}
return true;
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) {
} else {
//如果仅仅是用来判断网络连接
//则可以使用 cm.getActiveNetworkInfo().isAvailable();
NetworkInfo[] info = cm.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}