android 重启手机代码
第一种方法:
记得有一本书上介绍 说 0权限重启手机,原理是 在android 系统中,当显示一个toast,其实是将该toast挂载到窗体上, 而窗体又是系统的一个服务, 如果单位时间内不断地向窗体上挂载toast,就会不断的申请系统内存,导致系统重新启动。
- private void anr() {
- while (true) {
- System.out.println("running.. ");
- Toast toast = new Toast(getApplicationContext());
- View toastView = new View(getApplicationContext());
- toast.setView(toastView);
- toast.show();
- }
- }
使用小米3真机测试过之后,发现只会导致程序ANR,并不能实现设备重新启动.
第二种方法:
使用SU,改方法需要应用获取ROOT权限
http://stackoverflow.com/questions/5484535/runtime-exec-reboot-in-android
- public static void rebootSU() {
- Runtime runtime = Runtime.getRuntime();
- Process proc = null;
- OutputStreamWriter osw = null;
- StringBuilder sbstdOut = new StringBuilder();
- StringBuilder sbstdErr = new StringBuilder();
- String command="/system/bin/reboot";
- try { // Run Script
- proc = runtime.exec("su");
- osw = new OutputStreamWriter(proc.getOutputStream());
- osw.write(command);
- osw.flush();
- osw.close();
- } catch (IOException ex) {
- ex.printStackTrace();
- } finally {
- if (osw != null) {
- try {
- osw.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- try {
- if (proc != null)
- proc.waitFor();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- sbstdOut.append(new BufferedReader(new InputStreamReader(proc
- .getInputStream())));
- sbstdErr.append(new BufferedReader(new InputStreamReader(proc
- .getErrorStream())));
- if (proc.exitValue() != 0) {
- }
- }
第三,原理同上,需要ROOT权限, runtime是用来执行linux shell命令的,通过它可以实现对设备的相关操作
- private void restart() {
- String cmd = "su -c reboot";
- // String cmd = "su -c shutdown";
- try {
- Runtime.getRuntime().exec(cmd);
- } catch (IOException e) {
- new AlertDialog.Builder(getApplicationContext()).setTitle("Error").setMessage(
- e.getMessage()).setPositiveButton("OK", null).show();
- }
- }
第四种, 使用powerManger 来重启设备,同样的需要在配置文件中,添加权限 android.permission.REBOOT
http://developer.android.com/reference/android/os/PowerManager.html#reboot(java.lang.String)
- public void reboot (String reason)
- Added in API level 8
- Reboot the device. Will not return if the reboot is successful.
- Requires the REBOOT permission.
- Parameters
- reason code to pass to the kernel (e.g., "recovery") to request special boot modes, or null.