編輯:關於 Android 程式設計
打開一個應用時,總會先閃過一個啟動畫面。不同機型表現各異,有些甚至會出現一段黑屏,停留時間長短取決於冷啟動速度。這個畫面到底是什麼、從哪裡來、能不能換掉,本文從使用一路追到源碼。
答案藏在應用清單 AndroidManifest.xml 的 application 或 activity 節點的 android:theme 屬性裡。若沒有指定 theme,就會套用系統預設值。而主題中真正決定啟動畫面長相的,是 windowBackground 這個視窗屬性:
也就是說,應用啟動的那一刻,系統先把主題裡 windowBackground 指定的資源畫上去,當作佔位畫面,真正的第一幀 UI 準備好之後才替換掉。
系統預設的底色多半是白色或黑色。如果你的產品主色是白色,啟動時卻先閃一片黑,就會出現「先黑後白」的突兀轉場;若應用啟動很快,這個閃動更明顯,體驗打了折扣。既然啟動讀的是 windowBackground,直接覆寫它即可:
自訂一個主題並覆寫 windowBackground,啟動瞬間顯示的就是你指定的那張圖,放 logo 或品牌視覺都能強化辨識度。當然,也有越來越多產品把這個位置拿來放啟動廣告,那就是商業模式選擇了。
如果只想改畫面,學會覆寫就夠了。但想真正理解機制,得往源碼裡鑽。
我們點擊桌面圖示時,Home 應用其實是在呼叫 startActivity(intent),intent 中帶著套件名與類名。系統如何知道哪個 Activity 該出現在桌面?靠的是 manifest 中的這段宣告:
Home 把 intent 交給 ActivityManagerService,後者找出 action 為 MAIN、category 為 LAUNCHER 的 Activity 並顯示到介面。跟著 startActivity 往下看:
@Override
public void startActivity(Intent intent) {
this.startActivity(intent, null);
}
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
startActivityForResult(intent, -1);
}
}
public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
if (mParent == null) {
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult(mToken, mEmbeddedID, requestCode,
ar.getResultCode(), ar.getResultData());
}
cancelInputsAndStartExitTransition(options);
} else {
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}
兩個參數的 startActivity 最終都收束到 startActivityForResult,而它又呼叫 mInstrumentation.execStartActivity。往裡頭看:
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess();
int result = ActivityManagerNative.getDefault()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
關鍵是最後那句 ActivityManagerNative.getDefault().startActivity(...)。那 getDefault() 拿到了什麼?
static public IActivityManager getDefault() {
return gDefault.get();
}
private static final Singleton gDefault =
new Singleton() {
protected IActivityManager create() {
IBinder b = ServiceManager.getService("activity");
IActivityManager am = asInterface(b);
return am;
}
};
它從 ServiceManager 取出名稱為 "activity" 的服務,回傳一個 IActivityManager——這是跨進程通信的用戶端代理,真正的對端是 ActivityManagerService。當初 SystemServer 啟動時透過 setSystemProcess() 把 ActivityManagerService 以「activity」為名註冊進 ServiceManager,所以這裡拿到的其實就是 AMS 的遠端代理,實際執行程式碼在 AMS 那側。
AMS 的 startActivity 直接轉呼 startActivityAsUser,後者再呼叫 mStackSupervisor.startActivityMayWait:
final int startActivityMayWait(IApplicationThread caller, int callingUid,
String callingPackage, Intent intent, String resolvedType,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
IBinder resultTo, String resultWho, int requestCode, int startFlags,
ProfilerInfo profilerInfo, WaitResult outResult, Configuration config,
Bundle options, boolean ignoreTargetSecurity, int userId,
IActivityContainer iContainer, TaskRecord inTask) {
// ...
int res = startActivityLocked(caller, intent, resolvedType, aInfo,
voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
callingPid, callingUid, callingPackage, realCallingPid, realCallingUid,
startFlags, options, ignoreTargetSecurity, componentSpecified,
null, container, inTask);
// ...
}
startActivityLocked 內部又走向 startActivityUncheckedLocked,這裡負責解析 launchMode 與 task 歸屬:
final int startActivityUncheckedLocked(final ActivityRecord r,
ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession,
IVoiceInteractor voiceInteractor, int startFlags, boolean doResume,
Bundle options, TaskRecord inTask) {
final Intent intent = r.intent;
final boolean launchSingleTop = r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP;
final boolean launchSingleInstance = r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE;
final boolean launchSingleTask = r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK;
int launchFlags = intent.getFlags();
boolean newTask = false;
boolean keepCurTransition = false;
TaskRecord taskToAffiliate = launchTaskBehind && sourceRecord != null
? sourceRecord.task : null;
// 是否需要開新 task
if (r.resultTo == null && inTask == null && !addingToTask
&& (launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
newTask = true;
targetStack = computeStackFocus(r, newTask);
targetStack.moveToFront("startingNewTask");
// ... 建立或重用 TaskRecord
}
targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options);
if (!launchTaskBehind) {
mService.setFocusedActivityLocked(r, "startedActivity");
}
return ActivityManager.START_SUCCESS;
}
這裡先取出 launchMode(對應你在 manifest 中的設定)。從桌面啟動時 resultTo 為 null,表示不需要等待回傳結果;首次執行時找不到既有 task,於是 newTask 被設為 true,代表要新建一個 task 來承載這個 Activity。接著進入 targetStack.startActivityLocked:
final void startActivityLocked(ActivityRecord r, boolean newTask,
boolean doResume, boolean keepCurTransition, Bundle options) {
TaskRecord rTask = r.task;
r.putInHistory();
if (!isHomeStack() || numActivities() > 0) {
// 切換到新 task,或目標 Activity 的進程還沒起來時,顯示啟動預覽視窗
mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken,
r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
(r.info.flags & ActivityInfo.FLAG_SHOW_FOR_ALL_USERS) != 0,
r.userId, r.info.configChanges, task.voiceSession != null,
r.mLaunchTaskBehind);
boolean doShow = true;
if (newTask) {
if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
resetTaskIfNeededLocked(r, r);
doShow = topRunningNonDelayedActivityLocked(null) == r;
}
} else if (options != null
&& new ActivityOptions(options).getAnimationType()
== ActivityOptions.ANIM_SCENE_TRANSITION) {
doShow = false;
}
if (r.mLaunchTaskBehind) {
mWindowManager.setAppVisibility(r.appToken, true);
ensureActivitiesVisibleLocked(null, 0);
} else if (SHOW_APP_STARTING_PREVIEW && doShow) {
ActivityRecord prev = mResumedActivity;
if (prev != null) {
if (prev.task != r.task) {
prev = null;
} else if (prev.nowVisible) {
prev = null;
}
}
mWindowManager.setAppStartingWindow(
r.appToken, r.packageName, r.theme,
mService.compatibilityInfoForPackageLocked(r.info.applicationInfo),
r.nonLocalizedLabel, r.labelRes, r.icon, r.logo, r.windowFlags,
prev != null ? prev.appToken : null, showStartingIcon);
r.mStartingWindowShown = true;
}
}
if (doResume) {
mStackSupervisor.resumeTopActivitiesLocked(this, r, options);
}
}
穿過一連串條件判斷,我們終於看到 mWindowManager.setAppStartingWindow——曙光就在眼前:
@Override
public void setAppStartingWindow(IBinder token, String pkg, int theme,
CompatibilityInfo compatInfo, CharSequence nonLocalizedLabel,
int labelRes, int icon, int logo, int windowFlags,
IBinder transferFrom, boolean createIfNeeded) {
if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
"setAppStartingWindow()")) {
throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
}
wtoken.startingData = new StartingData(pkg, theme, compatInfo,
nonLocalizedLabel, labelRes, icon, logo, windowFlags);
Message m = mH.obtainMessage(H.ADD_STARTING, wtoken);
// 插到佇列最前面盡快處理
mH.sendMessageAtFrontOfQueue(m);
}
函式末尾送出了一個 ADD_STARTING 訊息。在 handleMessage 對應的分支裡,它會呼叫 WindowManagerPolicy.addStartingWindow 並取得一個 View。WindowManagerPolicy 是介面,其標準實作是 PhoneWindowManager,所以真正執行者是:
@Override
public View addStartingWindow(IBinder appToken, String packageName, int theme,
CompatibilityInfo compatInfo, CharSequence nonLocalizedLabel,
int labelRes, int icon, int logo, int windowFlags) {
PhoneWindow win = new PhoneWindow(context);
win.setIsStartingWindow(true);
final TypedArray ta = win.getWindowStyle();
if (ta.getBoolean(com.android.internal.R.styleable.Window_windowDisablePreview, false)
|| ta.getBoolean(com.android.internal.R.styleable.Window_windowShowWallpaper, false)) {
return null;
}
Resources r = context.getResources();
win.setTitle(r.getText(labelRes, nonLocalizedLabel));
win.setType(WindowManager.LayoutParams.TYPE_APPLICATION_STARTING);
win.setFlags(
windowFlags | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
windowFlags | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
params.setTitle("Starting " + packageName);
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
View view = win.getDecorView();
wm.addView(view, params);
return view.getParent() != null ? view : null;
}
這段做了幾件事:建立一個 PhoneWindow 當作顯示載體、標記 setIsStartingWindow(true)、設定標題與視窗型別、加上 NOT_TOUCHABLE 與 NOT_FOCUSABLE 等旗標(因為它只是一個假視窗,使用者不能觸碰也不能取得焦點),最後呼叫 getDecorView() 拿到要上屏的 View。每個 PhoneWindow 都有一個 DecorView,它會經由 installDecor 建立並交由 generateLayout 解析主題屬性:
private void installDecor() {
if (mDecor == null) {
mDecor = generateDecor();
mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
mDecor.setIsRootNamespace(true);
}
if (mContentParent == null) {
mContentParent = generateLayout(mDecor);
}
}
protected ViewGroup generateLayout(DecorView decor) {
// 套用目前主題的資料
TypedArray a = getWindowStyle();
if (getContainer() == null) {
if (mBackgroundDrawable == null) {
if (mBackgroundResource == 0) {
mBackgroundResource = a.getResourceId(
R.styleable.Window_windowBackground, 0);
}
}
final Drawable background;
if (mBackgroundResource != 0) {
background = getContext().getDrawable(mBackgroundResource);
} else {
background = mBackgroundDrawable;
}
mDecor.setWindowBackground(background);
return contentParent;
}
// ...
}
終於看到它解析 Window_windowBackground,並把結果設為 DecorView 的背景,最後透過 WindowManagerService 把這個 View 送上螢幕——啟動視窗於是也現身了。等應用真正啟動完成、第一幀內容準備好之後,這個 starting window 就會被移除,整個過程視覺上無縫銜接。
上面跳過了大量細節,其實這條鏈路更該被視為「應用啟動流程」的一部分,starting window 只是其中一小段。真實的啟動過程還會執行更多程式碼,但主幹邏輯一致:Home 發 intent → AMS 攔下並建立 ActivityRecord 與 task → WindowManager 依照主題屬性添加一個 starting window → 真正的 Activity 起來後再移除它。有興趣的話,值得把 ActivityThread 與 ActivityStack 相關源碼讀一遍。Read the fucking source code,這句話永遠有效。
Android 根據螢幕寬度按比例縮放圖片
ImageView 有 scaleType 屬性可以縮放圖片,讓圖片鋪滿螢幕寬度,但往往會出現壓縮或裁剪的情況。 ImageView 的 scaleType 屬性分別是
紙牌遊戲開發筆記(六):遊戲流程總覽
前面幾篇把紙牌遊戲的各個模組拆開講完了,這一篇就來把整個遊戲的流程串起來,看看從进入到結算的完整輪廓。 進入遊戲:輸入名稱 啟動遊戲後,首先會要求輸入玩家名稱,這個名稱後
一個 App 兩個圖示:模擬 QQ 郵箱的桌面捷徑方案
需求聽起來有點無厘頭:桌面上要有兩個圖示,看起來像兩個獨立 App,點不同圖示進入不同功能——就像 QQ 郵箱同時提供「郵箱」與「日曆」兩個入口那樣。本文記錄當時的實作思
舊手機變身電腦無線耳機/喇叭:SoundWire使用指南
SoundWire可把Android手機變成PC的無線聲卡或耳機。先在PC安裝伺服器端並記下Server Address,手機與PC連上同一Wi-Fi後開啟App搜尋或手