如何停止“ping”?以下代码是我尝试的方式,但它失败了。
private class pingWifi implements Runnable {
Process p = null;
@Override
public void run() {
// TODO Auto-generated method stub
/*
* WifiInfo info=mWifiManager.getConnectionInfo(); int
* ip=info.getIpAddress(); String ips=Formatter.formatIpAddress(ip);
*/
System.out.println("pingWifi runnable");
String[] shell = new String[] { "/system/bin/sh", "-c", " " };
Runtime run = Runtime.getRuntime();
shell[2] = "ping " + ipAddress;
try {
p = run.exec(shell);
if (p.waitFor() != 0) {
if (p.exitValue() == 1) {
byte[] buff = new byte[1024];
InputStream is = p.getErrorStream();
int c;
c = is.read(buff, 0, 1024);
System.out.println("ping error: " + new String(buff));
}
} else {
byte[] buff = new byte[1024];
InputStream is = p.getInputStream();
int c;
c = is.read(buff, 0, 1024);
System.out.println("ping result: " + new String(buff));
// wait for hardware
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
void stopProcess() {
if (p != null) {
p.destroy();
}else{
System.out.println("stopProcess: p==null");
}
}
}
private pingWifi mpingWifi = new pingWifi();
Thread wifiThread = new Thread(mpingWifi);
wifiThread.start();
在onPause中我调用了mpingWifi.stopProcess(),结果是“stopProcess:p == null”。我仍然可以在“ps”列表中找到ping进程。
我也想用“pkill ping”命令。但是Android shell中不支持“pkill”命令。我的目标是ping不是“停止”,直到“主页或后退”键事件发生。谢谢!
答案 0 :(得分:3)
尝试覆盖后退按钮并在其中调用Process.destroy()。
示例:
public void onBackPressed() {
p.destroy();
}