执行shell命令时显示进度条

时间:2014-04-09 19:43:42

标签: java android shell progressdialog

我试图在复制文件的过程中出现进度条(使用shell命令)。这是我的代码:

    copyProgress = new ProgressDialog(Activ.this);
    copyProgress.setMessage("Copying");
    copyProgress.show();  

    Process process1 = Runtime.getRuntime().exec(new String[] {"cp /sdcard/file /system"});
    Process process2 = Runtime.getRuntime().exec(new String[] {"cp /sdcard/file2 /system"});
    .......

    copyProgress.dismiss();

我需要执行多个不同的进程,因此如何在开始时显示进度对话框,并在最后一个文件成功完成复制时被解除。我尝试在procccess1之前显示对话框并在最后一个进程之后解除,但这不起作用。感谢。

显然我需要将它包装在一个Thread中。有人能告诉我我会怎么做吗?

1 个答案:

答案 0 :(得分:0)

原始代码中有几个问题。下面的代码处理后台线程上的进程运行,并使用waitFor调用检查它们的结果。无论如何,所有这一切都没有实际意义,因为你无法在没有root的情况下复制到/ system。

{   
   copyProgress = new ProgressDialog(Activ.this);
   copyProgress.setMessage("Copying");
   copyProgress.show();  
   new DoShellScriptyThingsAsyncThread().execute();
}

private class DoShellScriptyThingsAsyncThread extends AsyncTask<Void,Void,Void>
{

    @Override
    protected Void doInBackground(Void... params) {

        doCopy("file");
        publishProgress();
        doCopy("file2");
        publishProgress()
        return null;
    }

    private void  doCopy(String filename)
    {
        try    
    {            

        Process proc = Runtime.getRuntime().exec(new String[] {"cp /sdcard/"  +filename +" /system"});
        InputStream stdin = proc.getInputStream();
        InputStreamReader isr = new InputStreamReader(stdin);
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        System.out.println("<OUTPUT>");
        while ( (line = br.readLine()) != null)
            System.out.println(line);
        System.out.println("</OUTPUT>");
        int exitVal = proc.waitFor();            
        System.out.println("Process exitValue: " + exitVal);
    } catch (Throwable t)
      {
        t.printStackTrace();
        //Now do some thing if this fails - which it will because you are trying
        // to copy something to system
      }
}
    @Override
    protected void onProgressUpdate(Void... updateInteger)
    {
        //Update your progress dialog here!
        copyProgress.incrementProgress(5000);
    }
  }
    @Override
    protected void onPostExecute(Void result)
    {
        //Make your progress dialog go away here
        copyProgress.dismiss();
    }

};