Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 實現關機與重啟的兩種方法

編輯:關於 Android 程式設計

想要撰寫一個能讓裝置重新開機的 APK,關鍵在於權限。需要在 AndroidManifest.xml 中加上 android:sharedUserId="android.uid.system",並以系統簽名簽署應用,才能取得系統級權限。

方法一:透過 PowerManager

直接取得 PowerManager 服務並呼叫 reboot 即可:

private void rebootSystem(){
    PowerManager pManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    pManager.reboot("");
}

方法二:發送 REBOOT 廣播

構造一個帶有 nowait、interval、window 等額外參數的 ACTION_REBOOT 意圖,再送出廣播:

private void rebootSystem(){
    Intent reboot = new Intent(Intent.ACTION_REBOOT);
    reboot.putExtra("nowait", 1);
    reboot.putExtra("interval", 1);
    reboot.putExtra("window", 0);
    sendBroadcast(reboot);
}

兩種方式都需要系統權限與平台簽名,一般應用無法直接使用,主要應用於定制 ROM 或系統應用開發。實作時也建議加入確認對話框,避免使用者誤觸導致資料遺失。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved