检测管理,网络接口请求超时的时候可用调用单例的checkNetworkStatus方法
public class NetworkTimeoutManager {
private volatile static NetworkTimeoutManager ourInstance = null;
private volatile static boolean isChecking = false;
private NetworkTimeoutManager() {
}
public static NetworkTimeoutManager getInstance() {
if (ourInstance == null) {
synchronized (NetworkTimeoutManager.class) {
if (ourInstance == null) {
ourInstance = new NetworkTimeoutManager();
}
}
}
return ourInstance;
}
public void checkNetworkStatus() {
if (isChecking) {
return;
}
isChecking = true;
boolean pingSuccess = NetworkUtil.ping(10, 1, "223.5.5.5");
if (pingSuccess) {
//自身业务需要,服务器故障
SessionManager.getInstance().checkServerError(new DataObserver<VoidResp>() {
@Override
public void onNext(VoidResp response) {
isChecking = false;
}
@Override
public void onError(Throwable e) {
EventDispatcher.get().postEvent(new NetworkManager.checkServerErrorEvent());
isChecking = false;
}
});
} else {
EventDispatcher.get().postEvent(new NetworkManager.checkServerErrorEvent());
isChecking = false;
}
}
工具类方法
/**
* ping网络
*
* @param count ping次数 10
* @param time 超时时间(秒) 1
* @param url 地址
* @return 是否成功
*/
public static boolean ping(int count, int time, String url) {
if (url == null || url.length() <= 0) {
url = "223.5.5.5";// 阿里巴巴公共ip
}
String str = "ping -c " + count +
" -W " + time +
" " + url;
Runtime runtime = Runtime.getRuntime(); //新开一个进程执行脚本命令
Process ipProcess = null;
try {
ipProcess = runtime.exec(str);
InputStream input = ipProcess.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(input));
StringBuilder stringBuilder = new StringBuilder();
String content;
while ((content = in.readLine()) != null) {
stringBuilder.append(content);
}
int exitValue = ipProcess.waitFor();
if (exitValue == 0) {//0标识正常结束返回
//网络正常
return true;
} else {
//网络丢包严重,判断为网络未连接
//网络未丢包,判断为网络连接
return stringBuilder.indexOf("100% packet loss") == -1;
}
} catch (IOException | InterruptedException e) {
Logger.onJAVAError(e);
} finally {
//调用runtime执行脚本是非常消耗资源的,所以切忌不要频繁使用,使用完回收
if (ipProcess != null) {
ipProcess.destroy();
}
runtime.gc();
}
return false;
}
网友评论