package com.example.until;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetWork {
/**
* 判断网络是否连接
*
* @return
*/
public boolean isNetworkAvailable(Activity activity) {
Context context = activity.getApplicationContext();
// 获取所有连接管理对象(包括对wi-fi,net等连接的管理)
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null) {
return false;
} else {
// 获取NetworkInfo对象
NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
if (networkInfo != null && networkInfo.length > 0) {
for (int i = 0; i < networkInfo.length; i++) {
// 判断当前网络状态是否为连接状态NetworkInfo.State.CONNECTED系统提供的状态值
if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
/**
* 判断服务器是否连接
*
* @return
*/
public boolean isConnByHttp() {
boolean isConn = false;
URL url;
HttpURLConnection conn = null;
try {
url = new URL("http://" + APPFinal.getip());
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(50);
if (conn.getResponseCode() == 200) {
isConn = true;
}
} catch (MalformedURLException e) {
} catch (IOException e) {
} finally {
conn.disconnect();
}
return isConn;
}
}
网友评论