Android 12 雙擊power鍵啟動相機(jī)源碼解析

最近項目中接觸到需要修改手機(jī)按鍵的需求,整理一下分享給大家

雙擊power鍵大概流程

PhoneWindowManager.java類是 處理各種 power 鍵流程的地方奔浅,路徑如下:

\frameworks\base\services\core\java\com\android\server\policy\PhoneWindowManager.java

關(guān)鍵代碼:

case KeyEvent.KEYCODE_POWER: {
    EventLogTags.writeInterceptPower(
            KeyEvent.actionToString(event.getAction()),
            mPowerKeyHandled ? 1 : 0,
            mSingleKeyGestureDetector.getKeyPressCounter(KeyEvent.KEYCODE_POWER));
    // Any activity on the power button stops the accessibility shortcut
    result &= ~ACTION_PASS_TO_USER;
    isWakeKey = false; // wake-up will be handled separately
    if (down) {
        /*SPRD : add power debug log start*/
        Slog.d(TAG, "Receive Input KeyEvent of Powerkey down");
        /*SPRD : add power debug log end*/
        interceptPowerKeyDown(event, interactiveAndOn);
    } else {
        /*SPRD : add power debug log start*/
        Slog.d(TAG, "Receive Input KeyEvent of Powerkey up");
        /*SPRD : add power debug log end*/
        interceptPowerKeyUp(event, canceled);
    }
    break;
}

power鍵按下在interceptPowerKeyDown()執(zhí)行,松開的操作在interceptPowerKeyUp()中執(zhí)行interceptPowerKeyDown()方法中會調(diào)用GestureLauncherService.javainterceptPowerKeyDown()方法
關(guān)鍵代碼:

// The camera gesture will be detected by GestureLauncherService.
private boolean handleCameraGesture(KeyEvent event, boolean interactive) {
    // camera gesture.
    if (mGestureLauncherService == null) {
        return false;
    }
    mCameraGestureTriggered = false;
    final MutableBoolean outLaunched = new MutableBoolean(false);
    final boolean intercept =
            mGestureLauncherService.interceptPowerKeyDown(event, interactive, outLaunched);
    if (!outLaunched.value) {
        // If GestureLauncherService intercepted the power key, but didn't launch camera app,
        // we should still return the intercept result. This prevents the single key gesture
        // detector from processing the power key later on.
        return intercept;
    }
    mCameraGestureTriggered = true;
    if (mRequestedOrSleepingDefaultDisplay) {
        mCameraGestureTriggeredDuringGoingToSleep = true;
    }
    return true;
}

跟蹤看看GestureLauncherService.java 中 執(zhí)行 interceptPowerKeyDown()方法如下
GestureLauncherService.java诗良,路徑如下:

/frameworks/base/services/core/java/com/android/server/GestureLauncherService.java

關(guān)鍵代碼:

public boolean interceptPowerKeyDown(KeyEvent event, boolean interactive,
            MutableBoolean outLaunched, boolean isScreenOn) {
        if (event.isLongPress()) {
            // Long presses are sent as a second key down. If the long press threshold is set lower
            // than the double tap of sequence interval thresholds, this could cause false double
            // taps or consecutive taps, so we want to ignore the long press event.
            return false;
        }
        boolean launchCamera = false;
        boolean launchEmergencyGesture = false;
        boolean intercept = false;
        long powerTapInterval;
        synchronized (this) {
            powerTapInterval = event.getEventTime() - mLastPowerDown;
            mLastPowerDown = event.getEventTime();
            if (powerTapInterval >= POWER_SHORT_TAP_SEQUENCE_MAX_INTERVAL_MS) {
                // Tap too slow, reset consecutive tap counts.
                mPowerButtonConsecutiveTaps = 1;
                mPowerButtonSlowConsecutiveTaps = 1;
            } else if (powerTapInterval >= CAMERA_POWER_DOUBLE_TAP_MAX_TIME_MS) {
                // Tap too slow for shortcuts
                mPowerButtonConsecutiveTaps = 1;
                mPowerButtonSlowConsecutiveTaps++;
            } else {
                // Fast consecutive tap
                mPowerButtonConsecutiveTaps++;
                mPowerButtonSlowConsecutiveTaps++;
            }
            // Check if we need to launch camera or emergency gesture flows
            if (mEmergencyGestureEnabled) {
                // Commit to intercepting the powerkey event after the second "quick" tap to avoid
                // lockscreen changes between launching camera and the emergency gesture flow.
                if (mPowerButtonConsecutiveTaps > 1) {
                    intercept = interactive;
                }
                if (mPowerButtonConsecutiveTaps == EMERGENCY_GESTURE_POWER_TAP_COUNT_THRESHOLD) {
                    launchEmergencyGesture = true;
                }
            }
            if (mCameraDoubleTapPowerEnabled
                    && powerTapInterval < CAMERA_POWER_DOUBLE_TAP_MAX_TIME_MS
                    && mPowerButtonConsecutiveTaps == CAMERA_POWER_TAP_COUNT_THRESHOLD) {
                launchCamera = true;
                intercept = interactive;
            }
        }
        if (mPowerButtonConsecutiveTaps > 1 || mPowerButtonSlowConsecutiveTaps > 1) {
            Slog.i(TAG, Long.valueOf(mPowerButtonConsecutiveTaps)
                    + " consecutive power button taps detected, "
                    + Long.valueOf(mPowerButtonSlowConsecutiveTaps)
                    + " consecutive slow power button taps detected");
        }
        if (launchCamera) {
            Slog.i(TAG, "Power button double tap gesture detected, launching camera. Interval="
                    + powerTapInterval + "ms");
                // 調(diào)用開啟相機(jī)
                launchCamera = handleCameraGesture(false /* useWakelock */,
                        StatusBarManager.CAMERA_LAUNCH_SOURCE_POWER_DOUBLE_TAP);
            if (launchCamera) {
                mMetricsLogger.action(MetricsEvent.ACTION_DOUBLE_TAP_POWER_CAMERA_GESTURE,
                        (int) powerTapInterval);
                mUiEventLogger.log(GestureLauncherEvent.GESTURE_CAMERA_DOUBLE_TAP_POWER);
            }
        } else if (launchEmergencyGesture) {
            Slog.i(TAG, "Emergency gesture detected, launching.");
            launchEmergencyGesture = handleEmergencyGesture();
            mUiEventLogger.log(GestureLauncherEvent.GESTURE_EMERGENCY_TAP_POWER);
        }
        mMetricsLogger.histogram("power_consecutive_short_tap_count",
                mPowerButtonSlowConsecutiveTaps);
        mMetricsLogger.histogram("power_double_tap_interval", (int) powerTapInterval);

        outLaunched.value = launchCamera || launchEmergencyGesture;
        // Intercept power key event if the press is part of a gesture (camera, eGesture) and the
        // user has completed setup.
        return intercept && isUserSetupComplete();
    }

系統(tǒng)會對mCameraDoubleTapPowerEnabled 取值汹桦,核心是通過resources.getBoolean(com.android.internal.R.bool.config_cameraDoubleTapPowerGestureEnabled) 來取,
其實這個值是配置在/frameworks/base/core/res/res/values/config.xml中鉴裹,這里是為true的

<!-- Allow the gesture to double tap the power button twice to start the camera while the device
         is non-interactive. -->
<bool name="config_cameraDoubleTapPowerGestureEnabled">true</bool>

接下來會分別對power連續(xù)按2或者1次進(jìn)行判斷舞骆,如果mCameraDoubleTapPowerEnabled = true 會通過比較按鍵的時間powerTapInterval小于系統(tǒng)默認(rèn)時間(CAMERA_POWER_DOUBLE_TAP_MAX_TIME_MS=300毫秒),
mPowerButtonConsecutiveTaps計數(shù)加1,說明連續(xù)按power鍵径荔,或者延遲最大500毫秒內(nèi)連續(xù)按鍵督禽,系統(tǒng)預(yù)計用戶接下來可能會執(zhí)行一些操作,計數(shù)也會加1

static final long POWER_SHORT_TAP_SEQUENCE_MAX_INTERVAL_MS = 500;

static final long CAMERA_POWER_DOUBLE_TAP_MAX_TIME_MS = 300;

powerTapInterval = event.getEventTime() - mLastPowerDown;
mLastPowerDown = event.getEventTime();

if (mCameraDoubleTapPowerEnabled
                    && powerTapInterval < CAMERA_POWER_DOUBLE_TAP_MAX_TIME_MS
                    && mPowerButtonConsecutiveTaps == CAMERA_POWER_TAP_COUNT_THRESHOLD)

if (powerTapInterval < POWER_SHORT_TAP_SEQUENCE_MAX_INTERVAL_MS)

執(zhí)行完成之后會調(diào)用handleCameraGesture()方法調(diào)用開啟攝像機(jī)总处。

@VisibleForTesting
boolean handleCameraGesture(boolean useWakelock, int source) {
    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "GestureLauncher:handleCameraGesture");
    try {
        boolean userSetupComplete = isUserSetupComplete();
        if (!userSetupComplete) {
            if (DBG) {
                Slog.d(TAG, String.format(
                        "userSetupComplete = %s, ignoring camera gesture.",
                        userSetupComplete));
            }
            return false;
        }
        if (DBG) {
            Slog.d(TAG, String.format(
                    "userSetupComplete = %s, performing camera gesture.",
                    userSetupComplete));
        }

        if (useWakelock) {
            // Make sure we don't sleep too early
            mWakeLock.acquire(500L);
        }
        StatusBarManagerInternal service = LocalServices.getService(
                StatusBarManagerInternal.class);
        // 啟動相機(jī)
        service.onCameraLaunchGestureDetected(source);
        return true;
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    }
}

原生雙擊啟動相機(jī)流程差不多就是這樣狈惫,有任何問題歡迎留言討論

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市鹦马,隨后出現(xiàn)的幾起案子胧谈,更是在濱河造成了極大的恐慌,老刑警劉巖菠红,帶你破解...
    沈念sama閱讀 218,284評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件第岖,死亡現(xiàn)場離奇詭異,居然都是意外死亡试溯,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評論 3 395
  • 文/潘曉璐 我一進(jìn)店門郊酒,熙熙樓的掌柜王于貴愁眉苦臉地迎上來遇绞,“玉大人,你說我怎么就攤上這事燎窘∧∶觯” “怎么了?”我有些...
    開封第一講書人閱讀 164,614評論 0 354
  • 文/不壞的土叔 我叫張陵褐健,是天一觀的道長付鹿。 經(jīng)常有香客問我澜汤,道長,這世上最難降的妖魔是什么舵匾? 我笑而不...
    開封第一講書人閱讀 58,671評論 1 293
  • 正文 為了忘掉前任俊抵,我火速辦了婚禮,結(jié)果婚禮上坐梯,老公的妹妹穿的比我還像新娘徽诲。我一直安慰自己,他們只是感情好吵血,可當(dāng)我...
    茶點故事閱讀 67,699評論 6 392
  • 文/花漫 我一把揭開白布谎替。 她就那樣靜靜地躺著,像睡著了一般蹋辅。 火紅的嫁衣襯著肌膚如雪钱贯。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,562評論 1 305
  • 那天侦另,我揣著相機(jī)與錄音喷舀,去河邊找鬼。 笑死淋肾,一個胖子當(dāng)著我的面吹牛硫麻,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播樊卓,決...
    沈念sama閱讀 40,309評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼拿愧,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了碌尔?” 一聲冷哼從身側(cè)響起浇辜,我...
    開封第一講書人閱讀 39,223評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎唾戚,沒想到半個月后柳洋,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,668評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡叹坦,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,859評論 3 336
  • 正文 我和宋清朗相戀三年熊镣,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片募书。...
    茶點故事閱讀 39,981評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡绪囱,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出莹捡,到底是詐尸還是另有隱情鬼吵,我是刑警寧澤,帶...
    沈念sama閱讀 35,705評論 5 347
  • 正文 年R本政府宣布篮赢,位于F島的核電站齿椅,受9級特大地震影響琉挖,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜涣脚,卻給世界環(huán)境...
    茶點故事閱讀 41,310評論 3 330
  • 文/蒙蒙 一示辈、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧涩澡,春花似錦顽耳、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至粥帚,卻和暖如春胰耗,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背芒涡。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評論 1 270
  • 我被黑心中介騙來泰國打工柴灯, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人费尽。 一個月前我還...
    沈念sama閱讀 48,146評論 3 370
  • 正文 我出身青樓赠群,卻偏偏與公主長得像,于是被迫代替她去往敵國和親旱幼。 傳聞我的和親對象是個殘疾皇子查描,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,933評論 2 355

推薦閱讀更多精彩內(nèi)容