【问题标题】:Executing commands inside my app在我的应用程序中执行命令
【发布时间】:2018-05-21 16:48:19
【问题描述】:

我正在尝试从我的 android 应用程序执行命令,以便通过代码配置我设备的某些方面。 例如,我正在尝试使用以下代码(来自扩展 MainActivity 类的类)锁定我的设备:

Process p=Runtime.getRuntime().exec("su");
DataOutputStream dos = new DataOutputStream(p.getOutputStream());
dos.writeBytes("adb shell input keyevent 26");
dos.writeBytes("exit\n");
dos.flush();
dos.close();
p.waitFor();

当我运行它时,我收到:

java.io.Exception: Error running exec(). Command: [su] Working directory: null Environment: null

我的设备没有root。我已经尝试过其他方法来做到这一点,但都没有成功。

有什么想法吗?

【问题讨论】:

    标签: java android command-line


    【解决方案1】:

    我不认为你可以在不root你的应用程序的情况下做到这一点。因此,请尝试在有根设备上执行此操作。

    root 后,您可以尝试检查 root 权限,然后执行这些任务。

    here所述检查root权限:

     public boolean isRooted() {
        // get from build info
        String buildTags = android.os.Build.TAGS;
        if (buildTags != null && buildTags.contains("test-keys")) {
            return true;
        }
        // check if /system/app/Superuser.apk is present
        try {
            File file = new File("/system/app/Superuser.apk");
            if (file.exists()) {
                return true;
            }
        } catch (Exception exception) {
            // ignore
            exception.printStackTrace();
        }
        String[] commands = {
                "/system/xbin/which su",
                "/system/bin/which su",
                "which su"
        };
        for (String command : commands) {
            try {
                Runtime.getRuntime().exec(command);
                return true;
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }
        Log.d("message-startUp: ", "RootUtil");
        return false;
    }
    

    【讨论】:

    • 我已经用一个有根设备做了一个测试,至少,它要求root权限来执行命令。我不知道它是否适用于我的命令中明确的“su”。是否有可以在无根设备中执行的命令列表?
    【解决方案2】:

    我多次收到空工作目录错误,这一直是我的命令的问题。试试这个:

    Process proc = Runtime.getRuntime().exec(new String[] { "su", "-c", "input keyevent 26"});
    proc.waitFor();
    

    这至少应该解决“空环境”错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-20
      • 1970-01-01
      相关资源
      最近更新 更多