gpt4 book ai didi

android - 如何停止由 run.exec() 在 android 中启动的进程

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:07:46 24 4
gpt4 key购买 nike

如何停止“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 不会“停止”。谢谢!

最佳答案

尝试覆盖后退按钮按下并在其中调用 Process.destroy()。

例子:

public void onBackPressed() {
p.destroy();
}

关于android - 如何停止由 run.exec() 在 android 中启动的进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7962830/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com