【问题标题】:Android studio - How to use directly the terminal from java method?Android studio - 如何直接从java方法使用终端?
【发布时间】:2017-09-17 01:18:49
【问题描述】:

我是Android开发的新手,我尝试使用java方法访问Android手机的内部终端(/bin/bash,...)。

你知道这样的java方法是否存在吗?

谢谢

【问题讨论】:

    标签: java android bash sh


    【解决方案1】:

    我不完全确定您所说的“访问内部终端”是什么意思。但是,如果您想执行命令,请查看 Runtime 类的 documentation

    Here's 使用示例。

    【讨论】:

    • 我不想在主机操作系统上执行命令,而是在 Android 上。例如,我想从java方法中执行:“ls -l /data/app/*”来列出手机上安装的所有APK。
    • 我误会了。这就是我一直在寻找的方式。谢谢
    【解决方案2】:

    您可以使用RuntimeProcess 来完成您的任务。

    private static String executeCommand(String command) {
        Process process = null;
        BufferedReader reader = null;
        String result = "";
        try {
            String line;
            process = Runtime.getRuntime().exec(command);
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    
            while ((line = reader.readLine()) != null)
                result += line + "\n";
        } catch (final Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (process != null)
                    process.destroy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    

    其中 command 是任何可用的终端命令,例如 PING 8.8.8.8

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-10
      • 2014-11-16
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多