如何重启非root设备?

how to restart a non-rooted device?

在 SO 和 android 文档上阅读了很多答案后,似乎 不可能 在没有 root 权限的情况下 重启设备.

该应用甚至不询问我是否要授予权限。

// 1. Use permission in Manifest
<uses-permission android:name="android.permission.REBOOT" />

// 2. Request permission in MainActivity
if (ContextCompat.checkSelfPermission(this, Manifest.permission.REBOOT) != PackageManager.PERMISSION_GRANTED) {              
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.REBOOT}, 1);
}

// 3. Restart on button click
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
pm.reboot(null);

错误:

java.lang.SecurityException: Neither user 10201 nor current process has android.permission.REBOOT.

有没有我遗漏的解决方法?

非常感谢!

B.

不,您不能在没有 root 权限的情况下从您的 Android 应用程序执行此操作,但您可以使用以下命令从终端执行此操作:“adb reboot ”。但是如果你可以root你的设备然后你可以使用下面的代码来重启:

try {
    Process process = Runtime.getRuntime().exec("adb reboot");
} catch (IOException e) {
    e.printStackTrace();
}

如果这在 root 设备上也失败了,那么你可以通过请求 root 权限来尝试这个(在 android kitkat 4.4 上试过),

try{
            List<String> envList = new ArrayList<String>();
            Map<String, String> envMap = System.getenv();

            for (String envName : envMap.keySet()) {
                envList.add(envName + "=" + envMap.get(envName));
            }

            final String[] environment = (String[]) envList.toArray(new String[0]);

            String command= "reboot";
            Runtime.getRuntime().exec(
                    new String[]{"su", "-c", command},
                    environment).waitFor();
}catch(IOException e){
//catch exception
}