Java Runtime exec如何在不使用waitfor()的情况下确定进程何时终止?
我正在运行一个shell命令,它需要相当长的时间来执行,该命令运行起来没有任何问题,但一旦启动,我就无法让进程中止。我使用AsyncTask类运行命令以避免阻塞主线程,代码如下:Java Runtime exec如何在不使用waitfor()的情况下确定进程何时终止?,java,android,process,android-asynctask,runtime,Java,Android,Process,Android Asynctask,Runtime,我正在运行一个shell命令,它需要相当长的时间来执行,该命令运行起来没有任何问题,但一旦启动,我就无法让进程中止。我使用AsyncTask类运行命令以避免阻塞主线程,代码如下: private class Worker extends AsyncTask <String, Integer, Integer> { @Override protected Integer doInBackground (String... args) { Proc
private class Worker extends AsyncTask <String, Integer, Integer>
{
@Override
protected Integer doInBackground (String... args)
{
Process proc = runtime.getRuntime.exec ("some long process...");
while (/*process still running*/)
{
if (isCancellled()) proc.destroy();
}
return proc.exitValue();
}
.....
}
Worker w = new Worker();
w.execute();
w.cancel (true); // abort
私有类工作程序扩展异步任务
{
@凌驾
受保护的整数doInBackground(字符串…args)
{
processproc=runtime.getRuntime.exec(“某个长进程…”);
(/*进程仍在运行*/)
{
if(isCancelled())proc.destroy();
}
返回过程exitValue();
}
.....
}
工人w=新工人();
w、 执行();
w、 取消(真);//中止
如何在不阻塞AsyncTask线程的情况下确定进程何时完成?如何捕获AsyncTask取消信号并中止进程?我找到了一个简单的解决方案,可以在运行时进程启动后中止它,我只是在AsyncTask类中添加了对该进程的引用,当我需要中止shell命令时,我将调用进程上的
destroy
方法,它将终止:
private class Worker extends AsyncTask <String, Integer, Integer>
{
private Process proc;
@Override
protected Integer doInBackground (String... args)
{
try
{
this.proc = Runtime.getRuntime().exec (command);
this.proc.waitFor();
InputStream out = this.proc.getInputStream();
out.skip (out.available());
InputStream err = this.proc.getErrorStream();
err.skip (err.available());
}
catch (InterruptedException ex)
{
Log.i ("runCommand", "Interruped Exception");
ex.printStackTrace();
return -1;
}
catch (IOException ex)
{
ex.printStackTrace();
return -1;
}
return proc.exitValue();
}
public void abort()
{
if (this.proc != null) this.proc.destroy();
}
}
Worker w = new Worker();
w.execute();
w.abort(); // Terminates the process
私有类工作程序扩展异步任务
{
私有进程进程;
@凌驾
受保护的整数doInBackground(字符串…args)
{
尝试
{
this.proc=Runtime.getRuntime().exec(命令);
this.proc.waitFor();
InputStream out=this.proc.getInputStream();
out.skip(out.available());
InputStream err=this.proc.getErrorStream();
err.skip(err.available());
}
捕获(中断异常例外)
{
Log.i(“runCommand”、“中断异常”);
例如printStackTrace();
返回-1;
}
捕获(IOEX异常)
{
例如printStackTrace();
返回-1;
}
返回过程exitValue();
}
公共无效中止()
{
如果(this.proc!=null)this.proc.destroy();
}
}
工人w=新工人();
w、 执行();
w、 中止();//终止进程