我正在尝试构建一个可以 ping 服务器并获得延迟的应用程序。为了哪个
Process process = Runtime.getRuntime().exec(pingCommand);
命令调用system/bin/ping -c
命令。
因此,当我从 UI 中按下计算(我使用的按钮)时,它会卡住应用程序,直到执行完成。如何解决卡住问题,以便我可以在获取答案时关闭键盘?
最佳答案
为了避免 UI 卡住在线程中运行
new Thread(new Runnable() {
public void run() {
try {
// Send script into runtime process
Process process = Runtime.getRuntime().exec(pingCommand);
// ......
} catch (IOException e) {
e.printStackTrace();
} finally {
// .....
}
}
}).start();
}
替代方案
您可以像这样使用AsyncTask
:
private class YourTasksClass extends AsyncTask<Void, Void, String> {
private String cmd;
public YourTasksClass(String command) {
this.cmd = command;
}
@Override
protected String doInBackground(Void... voids) {
try {
Process process = Runtime.getRuntime().exec(cmd);
// ....
String someResult = "some kind of result";
return someResult;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result != null) {
Log.d("tag", "Result: " + result);
}
}
}
稍后在代码中,您可以通过以下方式调用它:
new YourTasksClass(pingCommand).execute();
关于java - Android Runtime.getRuntime().exec 命令导致应用程序在获取输出之前卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58518928/