Android實現關機、重啟裝置
阿新 • • 發佈:2018-11-01
1、關機
方法一:關機屬於系統級操作,所以需要獲得系統級的許可權。
android:sharedUserId="android.uid.system"
<uses-permission android:name="android.permission.SHUTDOWN/>
注意:一般的app開發是做不了系統級的應用,這裡的方法是使用了系統簽名來獲得許可權的(公司產品是基於原生Android定製的系統,所以我有對應的簽名檔案)
相關程式碼:
Intent intent = new Intent("android.intent.action.ACTION_REQUEST_SHUTDOWN"); intent.putExtra("android.intent.extra.KEY_CONFIRM", false); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); this.startActivity(intent);
方法二、以管理員身份執行命令
Runtime.getRuntime().exec(new String[]{"su","-c","reboot -p"});
或者
Runtime.getRuntime().exec(new String[]{"su","-c","shutdown"})
2、重啟
方法1、關機屬於系統級操作,所以需要獲得系統級的許可權。
android:sharedUserId="android.uid.system" <uses-permission android:name="android.permission.REBOOT"
相關程式碼:
PowerManager pm = (PowerManager) this.context.getSystemService(Context.POWER_SERVICE);
pm.reboot("");
同理,也需要系統簽名來獲得許可權。
方法2、以管理員身份執行命令
Runtime.getRuntime().exec("su -c reboot");