【问题标题】:Can't get runtime.exec working on android无法让 runtime.exec 在 android 上工作
【发布时间】:2012-06-22 21:15:29
【问题描述】:

我似乎无法让 runtime.exec 在我的 android 应用程序中工作。我已经尝试了许多 shell 实用程序,这是我正在使用的代码:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    filesPrinter = (Button) findViewById(R.id.print_files);
    filesPrinter.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            try {
                Process proc = Runtime.getRuntime().exec("ls");
                out = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
                in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
                String line;
                while((line = in.readLine()) != null) {
                    System.out.println(line);
                }
                System.out.println("Done reading");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
 }

我没有收到错误,但也没有在 logcat 中得到任何东西。

【问题讨论】:

  • 错误是什么?问题在哪里?您在发布之前阅读了 SO FAQ 吗?
  • @Astor 这个问题似乎是一个非常有效的问题,即使有关错误的更多详细信息确实会有所帮助。
  • 我已经进行了编辑,没有错误,但我没有得到任何输出到 logcat
  • 您是否尝试执行其他命令?例如尝试执行ls -l。你调试过那个代码吗?

标签: java android runtime.exec


【解决方案1】:

问题最终成为 eclipse logcat 的一个错误。使用 adb logcat,我可以看到应该输出的所有内容。出于某种原因,eclipse 上的 logcat 显示它已连接,但没有从模拟器接收任何应用程序级别的输出。

【讨论】:

  • 想一想,我认为 LogCat 不显示来自标准错误流的数据(这是 e.printStackTrace() 输出的地方)。改用System.out.println(Arrays.toString(e.getStackTrace()));,或者更好的是,任何Log 方法。
【解决方案2】:

也许您当前的工作目录(这是ls 不带任何参数扫描的目录)根本不包含文件。尝试提供路径作为命令参数。

【讨论】:

  • 我假设“什么都没有”是指“除了>>完成阅读
【解决方案3】:

认为您缺少proc.waitFor()....

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    filesPrinter = (Button) findViewById(R.id.print_files);
    filesPrinter.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            try {
                Process proc = Runtime.getRuntime().exec("ls");
                out = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
                in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
                String line;
                while((line = in.readLine()) != null) {
                    System.out.println(line);
                }
                System.out.println("Done reading");
                //
                proc.waitFor(); // THIS!!!
                //
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多