Android 重啟系統裝置 或APP
阿新 • • 發佈:2019-02-16
原始碼下載:
https://download.csdn.net/download/qq_31939617/10481352下載
第一種方法:
記得有一本書上介紹 說 0許可權重啟手機,原理是 在android 系統中,當顯示一個toast,其實是將該toast掛載到窗體上, 而窗體又是系統的一個服務, 如果單位時間內不斷地向窗體上掛載toast,就會不斷的申請系統記憶體,導致系統重新啟動。
[java] view plain copy print?- privatevoid 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
- publicstaticvoid 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命令的,通過它可以實現對裝置的相關操作
[java] view plain copy print?- privatevoid 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)