简体   繁体   中英

how to restart a non-rooted device?

After reading a lot of answers at SO and the android docs, it seems to be impossible to restart a device without root permission .

The app doesn't even ask me if I'd like to grand the permission.

// 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);

Error:

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

Is there any workaround that I missed?

Thank you very much!

B.

No, you can't do this from your Android application without root permissions but you can do this from the terminal by using the command: " adb reboot ". But if you can root your device then you can use the following code to reboot:

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

And if this too get failed on a rooted device then you can try with this by asking for root permission(tried on 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM