com.hadoopz.MyDroidLib.util.NetWorkUtils Maven / Gradle / Ivy
/*
* Copyright 2018 jw362j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hadoopz.MyDroidLib.util;
import android.content.Context;
import android.net.ConnectivityManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
*
* @author jw362j
*/
public class NetWorkUtils {
public enum InternetStatus {
SUCCESS, FAILED
}
public interface MyInternetDetecter {
void onInternetStatus(InternetStatus status);
}
/**
* 检测网络是否连接
*
* @return
*/
private boolean isNetworkAvailable(Context context) {
// 得到网络连接信息
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
// 去进行判断网络是否连接
if (manager.getActiveNetworkInfo() != null) {
return manager.getActiveNetworkInfo().isAvailable();
}
return false;
}
/* @author sichard
* @category 判断是否有外网连接(普通方法不能判断外网的网络是否连接,比如连接上局域网)
* @return
*/
public static void ping(String web_host, MyInternetDetecter detecter) {
String result = null;
try {
String ip = "www.google.com";// ping 的地址,可以换成任何一种可靠的外网
if (web_host != null) {
ip = web_host;
}
Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次
// 读取ping的内容,可以不加
InputStream input = p.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(input));
StringBuilder stringBuffer = new StringBuilder();
String content = "";
while ((content = in.readLine()) != null) {
stringBuffer.append(content).append("\n");
}
MyLogUtil.d("------ping-----", "result content : " + stringBuffer.toString());
// ping的状态
int status = p.waitFor();
if (status == 0) {
result = "success";
if (detecter != null) {
detecter.onInternetStatus(InternetStatus.SUCCESS);
}
return ;
} else {
result = "failed";
}
} catch (IOException e) {
result = "IOException:" + e.getMessage();
} catch (InterruptedException e) {
result = "InterruptedException:" + e.getMessage();
} finally {
MyLogUtil.d("----result---", "result = " + result);
}
if (detecter != null) {
detecter.onInternetStatus(InternetStatus.FAILED);
}
}
}