2

我似乎无法让 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 中得到任何东西。

4

3 回答 3

2

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

于 2012-06-22T21:46:04.903 回答
0

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

于 2012-06-22T21:22:16.037 回答
0

认为您缺少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();
            }
        }
    });
 }
于 2012-06-22T21:42:34.117 回答