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

客製化 Android:讓長按 Power 鍵直接關機

編輯:關於 Android 程式設計

在 Android 4.0.3 版本中,長按 Power 鍵會跳出關機選項對話框。然而在部分專案(例如 kiosk 單一功能裝置或特定商用設備)中,我們往往希望長按 Power 鍵能直接關機,而非跳出選擇對話框。由於 Android 4.0.3 原始碼中並無「長按直接關機」的內建選項,因此需要我們自行添加。

思路與涉及檔案

參照長按 Power 鍵跳出關機對話框的相關程式碼,可以發現涉及的關鍵檔案集中在:

  • framework/base/core/res/res/values/config.xml
  • framework/base/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java

第一步:新增關機行為常數

在 PhoneWindowManager.java 中新增一個常數 LONG_PRESS_POWER_OFF_NOW:

static final int LONG_PRESS_POWER_NOTHING = 0;
static final int LONG_PRESS_POWER_GLOBAL_ACTIONS = 1;
static final int LONG_PRESS_POWER_SHUT_OFF = 2;
static final int LONG_PRESS_POWER_OFF_NOW = 3;

其中各個變數即為長按 Power 鍵時的條件選項。

第二步:在 mPowerLongPress 中新增關機邏輯

找到 mPowerLongPress 這個 Runnable——它是長按 Power 鍵後系統啟動的執行緒,在其中加入新的 case 分支:

private final Runnable mPowerLongPress = new Runnable() {
    public void run() {
        // The context isn't read
        if (mLongPressOnPowerBehavior < 0) {
            mLongPressOnPowerBehavior = mContext.getResources().getInteger(
                    com.android.internal.R.integer.config_longPressOnPowerBehavior);
        }
        switch (mLongPressOnPowerBehavior) {
        case LONG_PRESS_POWER_NOTHING:
            break;
        case LONG_PRESS_POWER_GLOBAL_ACTIONS:
            mPowerKeyHandled = true;
            performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
            showGlobalActionsDialog();
            break;
        case LONG_PRESS_POWER_SHUT_OFF:
            mPowerKeyHandled = true;
            performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
            ShutdownThread.shutdown(mContext, true);
            break;
        case LONG_PRESS_POWER_OFF_NOW:  // 長按 Power 鍵關機程式碼
            Log.d(TAG, "-->> mPowerLongPress:run():LONG_PRESS_POWER_OFF_NOW");
            mPowerKeyHandled = true;
            performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
            ShutdownThread.shutdown(mContext, false);
            break;
        }
    }
};

第三步:修改 config.xml 的預設值

在第一步中我們新增了長按直接關機的處理程式碼,接著需要在 config.xml 中修改預設設定,將預設行為改為「長按直接關機」。找到以下設定,將預設的 1 改為 3:

<!--
<integer name="config_longPressOnPowerBehavior">1</integer>
-->
<integer name="config_longPressOnPowerBehavior">3</integer>

說明:ShutdownThread.shutdown(mContext, false) 中的第二個參數控制是否顯示關機動畫——設為 false 可實現無提示的直接關機。完成以上三個步驟後,重新編譯並燒錄,長按 Power 鍵便會直接關機。此客製化方式適用於需要簡化操作流程的專用裝置。

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