一个通用的完整网络连接状态检查工具
netState,ping dns,http
异步执行
使用低级api,保持独立通用
public class NetworkChecker {
private static final String TAG = "NetWorkChecker";
private static final String DNS_GOOGLE = "8.8.8.8";
private static final String DNS_DIANXIN = "114.114.114.114";
private static final String URL_BAIDU = "http://www.baidu.com";
private static final String URL_TENCENT = "http://www.qq.com";
private static boolean sPingSuccess = false;
private static boolean sHttpSuccess = false;
private static boolean sChecking = false; //当前是否正在检查网络中
private static ArrayList<checkEndListener> listeners = new ArrayList<>();
public interface checkEndListener {
public void onResult(boolean isNetWorkOk);
}
/**
* 检查网络的方法,通过网络回调来判断当前的网络是否是联通的
*
* @param listener
*/
public static synchronized void doCheck(Context context, final checkEndListener listener) {
Log.i(TAG, "doCheck start, sChecking = " + sChecking);
if (null == listener) {
Log.i(TAG, "listener is null , do nothing");
return;
}
listeners.add(listener);
if (sChecking) {
Log.i(TAG, "listener is checking , return and wait");
return;
}
if (!isNetworkConnected(context)) {
Log.i(TAG, " network is not connected, onCheckResult and return");
onCheckResult(false);
return;
}
sChecking = true;
sHttpSuccess = false;
sPingSuccess = false;
pingCheckAll(new checkEndListener() {
@Override
public void onResult(boolean isNetWorkOk) {
if (isNetWorkOk) {
Log.i(TAG, "ping success");
sPingSuccess = true;
if (sHttpSuccess) {
Log.i(TAG, " http check already end ,and success,so network is ok");