参考博客:
ping网络接口:https://blog.csdn.net/li13650639161/article/details/78465850
精确计算BigDecimal:https://www.cnblogs.com/LeoBoy/p/6056394.html
几乎参照大神代码,只是修改了下访问时间取值,我这里取的是平均值,效果展示:
1.AndroidManifes.xml文件中添加网络访问权限
2.检测网络实体类
/**
* @author jennifer
* @date 2019/3/20
*/
public class PingNetEntity {
/*
TODO:进行ping操作的ip
*/
private String ip;
/*
TODO:进行ping操作的次数
*/
private int pingCount;
/*
TODO:ping操作超时时间
*/
private int pingWtime;
/*
TODO:存储ping操作后得到的数据
*/
private StringBuffer resultBuffer;
/*
TODO:ping ip花费的时间
*/
private String pingTime;
/*
TODO:进行ping操作后的结果
*/
private boolean result;
public PingNetEntity(String ip, int pingCount, int pingWtime,StringBuffer resultBuffer) {
this.ip = ip;
this.pingWtime=pingWtime;
this.pingCount = pingCount;
this.resultBuffer = resultBuffer;
}
public String getPingTime() {
return pingTime;
}
public void setPingTime(String pingTime) {
this.pingTime = pingTime;
}
public StringBuffer getResultBuffer() {
return resultBuffer;
}
public void setResultBuffer(StringBuffer resultBuffer) {
this.resultBuffer = resultBuffer;
}
public int getPingCount() {
return pingCount;
}
public void setPingCount(int pingCount) {
this.pingCount = pingCount;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public boolean isResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
public int getPingWtime() {
return pingWtime;
}
public void setPingWtime(int pingWtime) {
this.pingWtime = pingWtime;
}
}
3.ping网络工具类
/**
* @author jennifer
* @date 2019/3/20
* @desc:ping工具类
*/
public class PingNet {
private static final String TAG = "PingNet";
/**
* @param pingNetEntity 检测网络实体类
* @return 检测后的数据
*/
public static PingNetEntity ping(PingNetEntity pingNetEntity) {
String line;
Process process = null;
BufferedReader successReader = null;
//ping -c 次数 -w 超时时间(s) ip
String command = "ping -c " + pingNetEntity.getPingCount() + " -w " + pingNetEntity.getPingWtime() + " " + pingNetEntity.getIp();
try {
process = Runtime.getRuntime().exec(command);
if (process == null) {
Log.e(TAG, "ping fail:process is null.");
append(pingNetEntity.getResultBuffer(), "ping fail:process is null.");
pingNetEntity.setPingTime(null);
pingNetEntity.setResult(false);
return pingNetEntity;
}
successReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
int count = 0;
BigDecimal sum = new BigDecimal(0);
while ((line = successReader.readLine()) != null) {
Log.e(TAG, line);
append(pingNetEntity.getResultBuffer(), line);
BigDecimal time = getTime(line);
if (time != null) {
sum = sum.add(time);
count++;
}
}
//时间取平均值,四舍五入保留两位小数
if (count > 0)
pingNetEntity.setPingTime((sum.divide(new BigDecimal(count), 2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString() + " ms"));
else
pingNetEntity.setPingTime(null);
int status = process.waitFor();
if (status == 0) {
Log.e(TAG, "exec cmd success:" + command);
append(pingNetEntity.getResultBuffer(), "exec cmd success:" + command);
pingNetEntity.setResult(true);
} else {
append(pingNetEntity.getResultBuffer(), "exec cmd fail.");
pingNetEntity.setPingTime(null);
pingNetEntity.setResult(false);
}
Log.e(TAG, "exec finished.");
append(pingNetEntity.getResultBuffer(), "exec finished.");
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Log.e(TAG, "ping exit.");
if (process != null) {
process.destroy();
}
if (successReader != null) {
try {
successReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Log.e(TAG, pingNetEntity.getResultBuffer().toString());
return pingNetEntity;
}
private static void append(StringBuffer stringBuffer, String text) {
if (stringBuffer != null) {
stringBuffer.append(text + "\n");
}
}
/**
* 获取ping接口耗时
*
* @param line
* @return BigDecimal避免float、double精准度问题
*/
private static BigDecimal getTime(String line) {
String[] lines = line.split("\n");
String time = null;
for (String l : lines) {
if (!l.contains("time="))
continue;
int index = l.indexOf("time=");
time = l.substring(index + "time=".length());
index = time.indexOf("ms");
time = time.substring(0, index);
Log.e(TAG, time);
}
return time == null ? null : new BigDecimal(time.trim());
}
}
4.xml页面布局
5.Activity中的使用,网络检测本身是耗时操作所以要在子线程中进行,获取到结果后在Handler中处理
public class EnvironmentTestActivity extends AppCompatActivity implements View.OnClickListener {
private TextView tvNet, tvContent;
private static final String BAIDU_API = "www.baidu.com";
private static final String CSDN_API = "www.csdn.net";
private static final String JIANSHU_API = "www.jianshu.com";
private static final int UPDATE_CONTENT = 1111;
private List lstApi;
private static final String TAG = "EnvironmentTestActivity";
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_environment_test);
initData();
initView();
initListener();
}
@SuppressLint("HandlerLeak")
private void initData() {
lstApi = new ArrayList<>();
lstApi.add(BAIDU_API);
lstApi.add(CSDN_API);
lstApi.add(JIANSHU_API);
handler = new Handler() {
@SuppressLint("SetTextI18n")
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case UPDATE_CONTENT:
tvContent.setText(tvContent.getText().toString() + msg.obj.toString());
break;
}
}
};
}
private void initView() {
tvNet = findViewById(R.id.tv_net);
tvContent = findViewById(R.id.tv_content);
}
private void initListener() {
tvNet.setOnClickListener(this);
tvContent.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_net:
for (final String api : lstApi) {
new Thread(new Runnable() {
@Override
public void run() {
PingNetEntity pingNetEntity = new PingNetEntity(api, 3, 5, new StringBuffer());
pingNetEntity = PingNet.ping(pingNetEntity);
Log.e("testPing",pingNetEntity.getIp());
Log.e("testPing","time="+pingNetEntity.getPingTime());
Log.e("testPing",pingNetEntity.isResult()+"");
Message msg = new Message();
msg.obj = pingNetEntity.getIp() + " 耗时:" + pingNetEntity.getPingTime() + "\n";
msg.what = UPDATE_CONTENT;
handler.sendMessage(msg);
}
}).start();
}
break;
}
}
}