java - 在我的应用程序内执行命令

标签 java android command-line

我正在尝试从我的 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 权限。我尝试过其他方法来做到这一点,但没有成功。

有什么想法吗?

最佳答案

我认为您无法在不root应用程序的情况下执行此操作。因此,请尝试在已取得 root 权限的设备上执行此操作。

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

如前所述检查 root 权限 here :

 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;
}

关于java - 在我的应用程序内执行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50453289/

相关文章:

java - 是否可以重新启动 springboot 应用程序?

java - 重复单词的正则表达式模式

java - 是否有任何框架/工具可用于创建基于模块的 Java Swing 应用程序?

android - 如何从任务中删除监听器?

linux - 如果文件名存在则发送电子邮件

java - 高效搜索非空交集(Java)

java - 将裁剪后的背景图像设置为自定义 ListView 项目

android - 如何在 Kotlin 中将波斯/阿拉伯数字转换为英文数字?

linux - 为什么我们需要执行权限,尽管我们可以使用 "bash script file"运行任何脚本而不需要它?

php - 如何从 Linux 上的日志文件中提取 XML block