运行时执行如何确定进程何时终止而不使用waitfor()?

时间:2015-05-04 21:03:22

标签: java android process android-asynctask runtime

我正在运行一个需要相当长时间才能执行的shell命令,该命令运行时没有任何麻烦,但是一旦启动就无法让进程中止。我正在使用AsyncTask类来运行命令以避免阻塞主线程,这里是代码:

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

如何在不阻塞AsyncTask线程的情况下找出进程何时完成?如何捕获AsyncTask取消信号并中止该过程?

1 个答案:

答案 0 :(得分:2)

我找到了一个简单的解决方案,在启动后中止运行时进程,我刚刚在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