【问题标题】:Show progressbar while executing shell commands执行 shell 命令时显示进度条
【发布时间】:2014-04-09 19:43:41
【问题描述】:

我试图在我复制文件的过程中显示一个进度条(使用 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之前显示对话框并在最后一个进程之后关闭,但这不起作用。谢谢。

显然我需要将它包装在一个线程中。谁能告诉我我会怎么做?

【问题讨论】:

  • 请显示您尝试实现此的代码
  • 你能说明你是如何尝试出现对话框的吗?
  • 我添加了我的进度对话框代码。问题是它根本没有出现。
  • 在 Java 中执行复制(在后台线程中,或者如果预计会很长,甚至服务中的一个线程)。这方面的例子很多。由于这样的副本将在中等大小的块中完成,这也为您提供了一种衡量文件内以及跨文件进度的现成方法。然后,您只需弄清楚如何让后台复制操作定期通知 UI 其进度。
  • @ChrisStratton 如果我以典型的 Java 方式执行此操作,那么当我将文件复制到 /system 时它仍然可以工作吗?我已经使用 shell 命令完成了它,因为我在命令之前调用了“su”,以便我获得写入 /system 的权限。

标签: java android shell progressdialog


【解决方案1】:

您的原始代码中有几个问题。下面的代码处理后台线程上进程的运行,并使用 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();
    }

};

【讨论】:

  • 你能举个例子说明我如何将它包装在一个线程中吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-30
  • 1970-01-01
  • 2023-01-27
相关资源
最近更新 更多