編輯:關於 Android 程式設計
用過原生 Android 手機的人都熟悉這個操作:同時按下音量減鍵與電源鍵,屏幕上便閃過一道白光,截屏完成。本文沿著源碼追問兩個問題:這個組合鍵是如何被識別的?識別之後系統又怎樣完成截屏?
既然在任何 App 頁面都能觸發截屏,說明這套邏輯屬於系統級的全局按鍵處理,而非某個應用的職責。
Android 中每個界面都是一個 Activity,界面的呈現依賴 Window 對象,每個 Window 實際上是 PhoneWindow 的實例,而每個 PhoneWindow 都關聯一個 PhoneWindowManager。按鍵事件在分發給應用之前,會先回調 PhoneWindowManager 的 dispatchUnhandledKey(),用來處理應用無意願或無能力消費的事件。
@Override
public KeyEvent dispatchUnhandledKey(WindowState win, KeyEvent event, int policyFlags) {
KeyEvent fallbackEvent = null;
if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
final KeyCharacterMap kcm = event.getKeyCharacterMap();
final int keyCode = event.getKeyCode();
final int metaState = event.getMetaState();
final boolean initialDown = event.getAction() == KeyEvent.ACTION_DOWN
&& event.getRepeatCount() == 0;
final FallbackAction fallbackAction;
if (initialDown) {
fallbackAction = kcm.getFallbackAction(keyCode, metaState);
} else {
fallbackAction = mFallbackActions.get(keyCode);
}
if (fallbackAction != null) {
final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
fallbackEvent = KeyEvent.obtain(
event.getDownTime(), event.getEventTime(), event.getAction(),
fallbackAction.keyCode, event.getRepeatCount(),
fallbackAction.metaState, event.getDeviceId(),
event.getScanCode(), flags, event.getSource(), null);
if (!interceptFallback(win, fallbackEvent, policyFlags)) {
fallbackEvent.recycle();
fallbackEvent = null;
}
if (initialDown) {
mFallbackActions.put(keyCode, fallbackAction);
} else if (event.getAction() == KeyEvent.ACTION_UP) {
mFallbackActions.remove(keyCode);
fallbackAction.recycle();
}
}
}
return fallbackEvent;
}
方法體中調用了 interceptFallback(),把按鍵的實際處理下發到那裡:
private boolean interceptFallback(WindowState win, KeyEvent fallbackEvent, int policyFlags) {
int actions = interceptKeyBeforeQueueing(fallbackEvent, policyFlags);
if ((actions & ACTION_PASS_TO_USER) != 0) {
long delayMillis = interceptKeyBeforeDispatching(win, fallbackEvent, policyFlags);
if (delayMillis == 0) {
return true;
}
}
return false;
}
其中 interceptKeyBeforeQueueing() 正是截屏按鍵的處理入口。
@Override
public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
if (!mSystemBooted) {
// 系統尚未啟動完成,所有按鍵都不響應
return 0;
}
...
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_MUTE: {
if (mUseTvRouting) {
// TV 上音量鍵不會傳給前台應用
result &= ~ACTION_PASS_TO_USER;
}
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
if (down) {
if (interactive
&& !mScreenshotChordVolumeDownKeyTriggered
&& (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
mScreenshotChordVolumeDownKeyTriggered = true;
mScreenshotChordVolumeDownKeyTime = event.getDownTime();
mScreenshotChordVolumeDownKeyConsumed = false;
cancelPendingPowerKeyAction();
interceptScreenshotChord();
}
} else {
mScreenshotChordVolumeDownKeyTriggered = false;
cancelPendingScreenshotChordAction();
}
}
...
return result;
}
這裡先判斷系統是否已啟動完成,未完成的話所有按鍵都失效。此外,HOME 鍵、MENU 鍵、任務列表鍵等特殊按鍵的處理也都在這個方法裡,後續可另文分析。
當音量減鍵按下時進入上述分支,同時檢測電源鍵是否也被按下。若確認是組合鍵,則執行:
if (interactive && !mScreenshotChordVolumeDownKeyTriggered
&& (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
mScreenshotChordVolumeDownKeyTriggered = true;
mScreenshotChordVolumeDownKeyTime = event.getDownTime();
mScreenshotChordVolumeDownKeyConsumed = false;
cancelPendingPowerKeyAction();
interceptScreenshotChord();
}
隨後進入 interceptScreenshotChord():
private void interceptScreenshotChord() {
if (mScreenshotChordEnabled
&& mScreenshotChordVolumeDownKeyTriggered
&& mScreenshotChordPowerKeyTriggered
&& !mScreenshotChordVolumeUpKeyTriggered) {
final long now = SystemClock.uptimeMillis();
if (now <= mScreenshotChordVolumeDownKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS
&& now <= mScreenshotChordPowerKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS) {
mScreenshotChordVolumeDownKeyConsumed = true;
cancelPendingPowerKeyAction();
mHandler.postDelayed(mScreenshotRunnable, getScreenshotChordLongPressDelay());
}
}
}
這裡判斷三個條件:截屏手勢開關已開啟、音量減鍵與電源鍵都被按下、音量加鍵沒有被按下。同時還有去抖動處理,要求在配置的時間窗口內完成組合,避免誤觸。滿足條件後投递一個延遲任務。
延遲時長由 getScreenshotChordLongPressDelay() 決定:
private long getScreenshotChordLongPressDelay() {
if (mKeyguardDelegate.isShowing()) {
// 鎖屏界面下需要按更久,避免誤觸
return (long) (KEYGUARD_SCREENSHOT_CHORD_DELAY_MULTIPLIER
* ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
}
return ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout();
}
延遲到點後,mScreenshotRunnable 的 run() 被執行,方法體只有一行:
private final Runnable mScreenshotRunnable = new Runnable() {
@Override
public void run() {
takeScreenshot();
}
};
private void takeScreenshot() {
synchronized (mScreenshotLock) {
if (mScreenshotConnection != null) {
return;
}
ComponentName cn = new ComponentName("com.android.systemui",
"com.android.systemui.screenshot.TakeScreenshotService");
Intent intent = new Intent();
intent.setComponent(cn);
ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
synchronized (mScreenshotLock) {
if (mScreenshotConnection != this) {
return;
}
Messenger messenger = new Messenger(service);
Message msg = Message.obtain(null, 1);
final ServiceConnection myConn = this;
Handler h = new Handler(mHandler.getLooper()) {
@Override
public void handleMessage(Message msg) {
synchronized (mScreenshotLock) {
if (mScreenshotConnection == myConn) {
mContext.unbindService(mScreenshotConnection);
mScreenshotConnection = null;
mHandler.removeCallbacks(mScreenshotTimeout);
}
}
}
};
msg.replyTo = new Messenger(h);
msg.arg1 = msg.arg2 = 0;
// 記錄狀態欄與導航欄是否可見,供後續截圖時決定是否一併截入
if (mStatusBar != null && mStatusBar.isVisibleLw()) msg.arg1 = 1;
if (mNavigationBar != null && mNavigationBar.isVisibleLw()) msg.arg2 = 1;
try {
messenger.send(msg);
} catch (RemoteException e) {
}
}
}
@Override
public void onServiceDisconnected(ComponentName name) { }
};
if (mContext.bindServiceAsUser(intent, conn, Context.BIND_AUTO_CREATE,
UserHandle.CURRENT)) {
mScreenshotConnection = conn;
mHandler.postDelayed(mScreenshotTimeout, 10000);
}
}
}
WindowManager 服務並不親自截屏,而是綁定 SystemUI 中的 TakeScreenshotService,通過 Messenger 投递一條消息並附上回調。同時它會把狀態欄、導航欄的可見狀態編碼進 msg.arg1 與 msg.arg2,後續決定是否把這兩塊也截進來。此外還設了 10 秒超時保護,避免服務無響應導致連接洩漏。
public class TakeScreenshotService extends Service {
private static GlobalScreenshot mScreenshot;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
final Messenger callback = msg.replyTo;
if (mScreenshot == null) {
mScreenshot = new GlobalScreenshot(TakeScreenshotService.this);
}
mScreenshot.takeScreenshot(new Runnable() {
@Override
public void run() {
Message reply = Message.obtain(null, 1);
try {
callback.send(reply);
} catch (RemoteException e) {
}
}
}, msg.arg1 > 0, msg.arg2 > 0);
}
}
};
@Override
public IBinder onBind(Intent intent) {
return new Messenger(mHandler).getBinder();
}
}
收到消息後創建 GlobalScreenshot 並調用其 takeScreenshot(),完成後通過 Messenger 回執通知 WindowManager 解除綁定。
/** 截取當前屏幕顯示並播放動畫 */
void takeScreenshot(Runnable finisher, boolean statusBarVisible, boolean navBarVisible) {
// Surface API 只能按設備自然方向截屏,這裡需要處理旋轉
mDisplay.getRealMetrics(mDisplayMetrics);
float[] dims = {mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels};
float degrees = getDegreesForRotation(mDisplay.getRotation());
boolean requiresRotation = (degrees > 0);
if (requiresRotation) {
mDisplayMatrix.reset();
mDisplayMatrix.preRotate(-degrees);
mDisplayMatrix.mapPoints(dims);
dims[0] = Math.abs(dims[0]);
dims[1] = Math.abs(dims[1]);
}
// 執行截屏
mScreenBitmap = SurfaceControl.screenshot((int) dims[0], (int) dims[1]);
if (mScreenBitmap == null) {
notifyScreenshotError(mContext, mNotificationManager);
finisher.run();
return;
}
if (requiresRotation) {
// 按當前方向旋轉截圖
Bitmap ss = Bitmap.createBitmap(mDisplayMetrics.widthPixels,
mDisplayMetrics.heightPixels, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(ss);
c.translate(ss.getWidth() / 2, ss.getHeight() / 2);
c.rotate(degrees);
c.translate(-dims[0] / 2, -dims[1] / 2);
c.drawBitmap(mScreenBitmap, 0, 0, null);
c.setBitmap(null);
// 回收原圖
mScreenBitmap.recycle();
mScreenBitmap = ss;
}
// 截圖不包含 alpha 通道,並預熱以獲得更好的繪製性能
mScreenBitmap.setHasAlpha(false);
mScreenBitmap.prepareToDraw();
startAnimation(finisher, mDisplayMetrics.widthPixels,
mDisplayMetrics.heightPixels, statusBarVisible, navBarVisible);
}
前面提到的 statusBarVisible 與 navBarVisible 正是在這裡派上用場:若狀態欄可見,截圖時會一併截入;導航欄同理。
public static Bitmap screenshot(int width, int height) {
// TODO: 應把 display 作為參數傳入
IBinder displayToken = SurfaceControl.getBuiltInDisplay(
SurfaceControl.BUILT_IN_DISPLAY_ID_MAIN);
return nativeScreenshot(displayToken, new Rect(), width, height, 0, 0, true, false,
Surface.ROTATION_0);
}
nativeScreenshot() 是一個 native 方法,真正的實現位於 JNI 層,涉及 SurfaceFlinger 的圖層合成,這裡不展開。值得注意的是返回值是 Bitmap——熟悉 Android 繪製機制的人都清楚,屏幕上一切可見內容在內存中的形態都是 Bitmap。
截屏失敗時走的是通知分支:
static void notifyScreenshotError(Context context, NotificationManager nManager) {
Resources r = context.getResources();
// 清理已有通知,重新組裝並展示
Notification.Builder b = new Notification.Builder(context)
.setTicker(r.getString(R.string.screenshot_failed_title))
.setContentTitle(r.getString(R.string.screenshot_failed_title))
.setContentText(r.getString(R.string.screenshot_failed_text))
.setSmallIcon(R.drawable.stat_notify_image_error)
.setWhen(System.currentTimeMillis())
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setCategory(Notification.CATEGORY_ERROR)
.setAutoCancel(true)
.setColor(context.getColor(com.android.internal.R.color.system_notification_accent_color));
Notification n = new Notification.BigTextStyle(b)
.bigText(r.getString(R.string.screenshot_failed_text))
.build();
nManager.notify(R.id.notification_screenshot, n);
}
/** 截屏後播放動畫 */
private void startAnimation(final Runnable finisher, int w, int h,
boolean statusBarVisible, boolean navBarVisible) {
mScreenshotView.setImageBitmap(mScreenBitmap);
mScreenshotLayout.requestFocus();
if (mScreenshotAnimation != null) {
mScreenshotAnimation.end();
mScreenshotAnimation.removeAllListeners();
}
mWindowManager.addView(mScreenshotLayout, mWindowLayoutParams);
ValueAnimator dropInAnim = createScreenshotDropInAnimation();
ValueAnimator fadeOutAnim = createScreenshotDropOutAnimation(
w, h, statusBarVisible, navBarVisible);
mScreenshotAnimation = new AnimatorSet();
mScreenshotAnimation.playSequentially(dropInAnim, fadeOutAnim);
mScreenshotAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
// 動畫結束後再保存,避免阻塞動畫
saveScreenshotInWorkerThread(finisher);
mWindowManager.removeView(mScreenshotLayout);
mScreenBitmap = null;
mScreenshotView.setImageBitmap(null);
}
});
mScreenshotLayout.post(new Runnable() {
@Override
public void run() {
// 播放快門聲
mCameraSound.play(MediaActionSound.SHUTTER_CLICK);
mScreenshotView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
mScreenshotView.buildLayer();
mScreenshotAnimation.start();
}
});
}
動畫由「落下」與「淡出」兩段串聯組成,並在開始時播放快門音效。真正的保存被安排在動畫結束之後,通過工作線程異步執行,避免影響動畫流暢度。
/** 新建工作線程,把截圖保存到媒體庫 */
private void saveScreenshotInWorkerThread(Runnable finisher) {
SaveImageInBackgroundData data = new SaveImageInBackgroundData();
data.context = mContext;
data.image = mScreenBitmap;
data.iconSize = mNotificationIconSize;
data.finisher = finisher;
data.previewWidth = mPreviewWidth;
data.previewHeight = mPreviewHeight;
if (mSaveInBgTask != null) {
mSaveInBgTask.cancel(false);
}
mSaveInBgTask = new SaveImageInBackgroundTask(mContext, data,
mNotificationManager, R.id.notification_screenshot).execute(data);
}
而「截屏成功」這條通知,其實在 SaveImageInBackgroundTask 的構造方法中就已發出——那是一個「正在保存」的中間態通知:
SaveImageInBackgroundTask(Context context, SaveImageInBackgroundData data,
NotificationManager nManager, int nId) {
...
mNotificationId = nId;
mNotificationManager = nManager;
final long now = System.currentTimeMillis();
mNotificationBuilder = new Notification.Builder(context)
.setTicker(r.getString(R.string.screenshot_saving_ticker))
.setContentTitle(r.getString(R.string.screenshot_saving_title))
.setContentText(r.getString(R.string.screenshot_saving_text))
.setSmallIcon(R.drawable.stat_notify_image)
.setWhen(now)
.setColor(r.getColor(com.android.internal.R.color.system_notification_accent_color));
mNotificationStyle = new Notification.BigPictureStyle()
.bigPicture(picture.createAshmemBitmap());
mNotificationBuilder.setStyle(mNotificationStyle);
// 鎖屏等「公開」場景下展示相同信息,但隱去截圖本身
mPublicNotificationBuilder = new Notification.Builder(context)
.setContentTitle(r.getString(R.string.screenshot_saving_title))
.setContentText(r.getString(R.string.screenshot_saving_text))
.setCategory(Notification.CATEGORY_PROGRESS)
.setWhen(now)
.setColor(...);
mNotificationBuilder.setPublicVersion(mPublicNotificationBuilder.build());
Notification n = mNotificationBuilder.build();
n.flags |= Notification.FLAG_NO_CLEAR;
mNotificationManager.notify(nId, n);
...
}
PhoneWindowManager.dispatchUnhandledKey() 接管應用未處理的按鍵,其中也包含音量減鍵與電源鍵的組合。interceptKeyBeforeQueueing() → interceptScreenshotChord() 的層層判斷與去抖動,確認手勢成立後投递延遲任務。takeScreenshot() 綁定 SystemUI 的 TakeScreenshotService,由它調用 GlobalScreenshot 完成實際工作。SurfaceControl.screenshot(),底層依賴 SurfaceFlinger。這條鏈路給人的啟發在於職責劃分:WindowManager 服務只負責「識別手勢、選擇執行者」,具體的截屏、旋轉、動畫、通知全部收攏到 SystemUI 進程,既減輕了 system_server 的負擔,也讓截屏相關的 UI 邏輯便於獨立演進。
自定義帶數字角標的 CheckBox:selector 與自定義 View 兩種實作
近期手上的專案一直在做即時通訊,聊天功能裡「發圖片」幾乎是標配。既然要做,不妨先看看成熟產品是怎麼處理的——打開 QQ 走一遍選圖流程,會發現每張縮圖的右上角都掛著一個小
vivo X7怎麼截圖?快捷鍵、超級截屏與長截圖三種方式
vivo X7 是主打小螢幕、纖薄機身、拍照與 HiFi 音質的機型,售價 2498 元。新機剛拿到手,最常先摸清楚的就是截圖怎麼操作。好消息是它不只一種方式,其中「超級
Android Glide 源碼解析:一張圖片的完整加載旅程
一、功能與基本用法 Glide 是 Google 官方推薦的圖片加載庫,相比 Picasso 在生命周期管理、解碼效率與資源複用上都有不少改進。本文基於 GitHub 上
Android 自定義 View:左右滑動選擇出生年份
在一些個人資料頁面中,出生年份的選擇通常採用滑動效果。用戶左右滑動時,中間數字會放大,兩側數字會縮小,最終停留在選中的年份上。這種效果可以通過自定義 View 實現。