Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

為 Android 系統加入「重新啟動」選項

原廠 ROM 的電源選單往往只有關機,想加一個「重新啟動」需要動到 framework 的兩個檔案。以下依序說明。

一、GlobalActions:在電源選單中新增項目

修改 com.android.internal.policy.impl.GlobalActions,在 items 集合中加入一個 SinglePressAction,並在 onPress() 中觸發重啟:

new SinglePressAction(
        com.android.internal.R.drawable.ic_lock_power_off,
        R.string.global_action_power_reboot) {

    public void onPress() {
        ShutdownThread.reboot(mContext, null, true);
    }

    public boolean showDuringKeyguard() {
        return true;
    }

    public boolean showBeforeProvisioning() {
        return true;
    }
});

三個方法的意義分別是:按下後執行的動作、鎖屏狀態下是否仍顯示、以及裝置尚未完成開機設定引導時是否顯示。

二、ShutdownThread:加入 reboot 的處理邏輯

接著在 com.android.internal.app.ShutdownThread 中補上對應的重啟處理。核心是在 shutdown 流程中多帶一個 isReboot 參數,並據此切換對話框的標題與訊息文字:

/**
 * Request a clean shutdown, waiting for subsystems to clean up their
 * state etc. Must be called from a Looper thread in which its UI
 * is shown.
 *
 * @param context Context used to display the shutdown progress dialog.
 * @param confirm true if user confirmation is needed before shutting down.
 * @param isReboot true if reboot rather than shutdown is requested.
 */
public static void shutdown(final Context context, boolean confirm, boolean isReboot) {
    mReboot = isReboot;

    // 確保只有一個线程在執行关机流程,後續呼叫直接返回
    synchronized (sIsStartedGuard) {
        if (sIsStarted) {
            Log.d(TAG, "Request to shutdown already running, returning.");
            return;
        }
    }

    if (confirm) {
        final AlertDialog dialog = new AlertDialog.Builder(context)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle(mReboot ? com.android.internal.R.string.global_action_power_reboot
                              : com.android.internal.R.string.global_action_power_off)
            .setMessage(mReboot ? com.android.internal.R.string.reboot_confirm
                                : com.android.internal.R.string.shutdown_confirm)
            .setPositiveButton(com.android.internal.R.string.yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    beginShutdownSequence(context);
                }
            })
            .setNegativeButton(com.android.internal.R.string.no, null)
            .create();
    } else {
        beginShutdownSequence(context);
    }
}

關鍵在於 mReboot 這個旗標:它決定確認對話框顯示「重新啟動」還是「關機」的字樣,後續的 beginShutdownSequence() 也會依此在關機流程末端呼叫 reboot 而非 shutdown。改完重新編譯 framework,電源長按選單中就會多出重啟項目。

Copyright © Linux教程網 All Rights Reserved