前置知識(shí)
當(dāng)Android系統(tǒng)啟動(dòng)時(shí),首先會(huì)創(chuàng)建Zygote進(jìn)程,Zygote進(jìn)程啟動(dòng)后會(huì)fork若干其他的進(jìn)程,例如SystemServer進(jìn)程,Launcher進(jìn)程。
創(chuàng)建SystemServer進(jìn)程后會(huì)創(chuàng)建SystemServiceManager,啟動(dòng)很多系統(tǒng)服務(wù),例ActivityTaskManagerService,ActivityManagerService,PackageManagerService等。
其中Launcher桌面實(shí)際上就是一個(gè)Activity,當(dāng)我們點(diǎn)擊桌面icon,也是通過startActivity來啟動(dòng)App的。
在桌面點(diǎn)擊一個(gè)APP圖標(biāo)啟動(dòng)APP的過程中,涉及到了跨進(jìn)程通信,APP進(jìn)程創(chuàng)建,Application和Activity的創(chuàng)建和啟動(dòng)等內(nèi)容。
本篇文章主要分析點(diǎn)擊桌面App圖標(biāo)到ActivityTaskManagerService的過程。
涉及到的幾個(gè)類
- packages/apps/Launcher3/src/com/android/launcher3/Launcher.java
- frameworks/base/core/java/android/app/Instrumentation.java
- frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
具體過程:
1.找到Launcher桌面的APP圖標(biāo)入口位置
- Launcher是一個(gè)Activity,加載的布局為R.layout.launcher
- launcher.xml中的
layout="@layout/all_apps"引入了LauncherAllAppsContainerView,其中layout="@layout/all_apps_rv_layout"引入了AllAppsRecyclerView - 在AllAppsContainerView中為其設(shè)置的adapter是AllAppsGridAdapter,點(diǎn)擊事件由launcher.getItemOnClickListener()獲取,通過ItemClickHandler.INSTANCE單例方法獲取點(diǎn)擊事件
- 最終調(diào)用ItemClickHandler的onClick->startAppShortcutOrInfoActivity->launcher.startActivitySafely
packages/apps/Launcher3/src/com/android/launcher3/touch/ItemClickHandler.java
private static void onClick(View v, String sourceContainer) {
if (v.getWindowToken() == null) return;
Launcher launcher = Launcher.getLauncher(v.getContext());
if (!launcher.getWorkspace().isFinishedSwitchingState()) return;
Object tag = v.getTag();
if (tag instanceof WorkspaceItemInfo) {
onClickAppShortcut(v, (WorkspaceItemInfo) tag, launcher, sourceContainer);
} else if (tag instanceof FolderInfo) {
if (v instanceof FolderIcon) {
onClickFolderIcon(v);
}
} else if (tag instanceof AppInfo) {
//點(diǎn)擊App圖標(biāo)
startAppShortcutOrInfoActivity(v, (AppInfo) tag, launcher,
sourceContainer == null ? CONTAINER_ALL_APPS: sourceContainer);
} else if (tag instanceof LauncherAppWidgetInfo) {
if (v instanceof PendingAppWidgetHostView) {
onClickPendingWidget((PendingAppWidgetHostView) v, launcher);
}
}
}
private static void startAppShortcutOrInfoActivity(View v, ItemInfo item, Launcher launcher,
@Nullable String sourceContainer) {
Intent intent;
if (item instanceof PromiseAppInfo) {
PromiseAppInfo promiseAppInfo = (PromiseAppInfo) item;
intent = promiseAppInfo.getMarketIntent(launcher);
} else {
intent = item.getIntent();
}
if (intent == null) {
throw new IllegalArgumentException("Input must have a valid intent");
}
if (item instanceof WorkspaceItemInfo) {
WorkspaceItemInfo si = (WorkspaceItemInfo) item;
if (si.hasStatusFlag(WorkspaceItemInfo.FLAG_SUPPORTS_WEB_UI)
&& Intent.ACTION_VIEW.equals(intent.getAction())) {
intent = new Intent(intent);
intent.setPackage(null);
}
}
if (v != null && launcher.getAppTransitionManager().supportsAdaptiveIconAnimation()) {
FloatingIconView.fetchIcon(launcher, v, item, true /* isOpening */);
}
//調(diào)用
launcher.startActivitySafely(v, intent, item, sourceContainer);
}
2.startActivitySafely->startActivityForResult
packages/apps/Launcher3/src/com/android/launcher3/Launcher.java
public boolean startActivitySafely(View v, Intent intent, @Nullable ItemInfo item, @Nullable String sourceContainer) {
//...
//添加FLAG_ACTIVITY_NEW_TASK
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
boolean isShortcut = (item instanceof WorkspaceItemInfo)
&& (item.itemType == Favorites.ITEM_TYPE_SHORTCUT
|| item.itemType == Favorites.ITEM_TYPE_DEEP_SHORTCUT)
&& !((WorkspaceItemInfo) item).isPromise();
if (isShortcut) {
//點(diǎn)擊Shortcut啟動(dòng)activity
// Shortcuts need some special checks due to legacy reasons.
startShortcutIntentSafely(intent, optsBundle, item, sourceContainer);
} else if (user == null || user.equals(Process.myUserHandle())) {
//點(diǎn)擊app圖標(biāo)啟動(dòng)app
// Could be launching some bookkeeping activity
startActivity(intent, optsBundle);
AppLaunchTracker.INSTANCE.get(this).onStartApp(intent.getComponent(),
Process.myUserHandle(), sourceContainer);
} else {
getSystemService(LauncherApps.class).startMainActivity(
intent.getComponent(), user, intent.getSourceBounds(), optsBundle);
AppLaunchTracker.INSTANCE.get(this).onStartApp(intent.getComponent(), user,
sourceContainer);
}
return true;
} catch (NullPointerException|ActivityNotFoundException|SecurityException e) {
...
}
return false;
}
public void startActivity(Intent intent, @Nullable Bundle options) {
//本質(zhì)上還是通過startActivityForResult啟動(dòng)activity
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
startActivityForResult(intent, -1);
}
}
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) {
//此時(shí)需要啟動(dòng)的Activity的parent還是null
if (mParent == null) {
options = transferSpringboardActivityOptions(options);
//Instrumentation執(zhí)行了execStartActivity方法
//mMainThread:Launcher所在的進(jìn)程
//mMainThread.getApplicationThread():獲取mMainThread.getApplicationThread(),ApplicationThread 繼承自 Stub,也就是 Binder,用于進(jìn)程間通信
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());
}
if (requestCode >= 0) {
mStartedActivity = true;
}
cancelInputsAndStartExitTransition(options);
} else {
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}
3.Instrumentation.execStartActivity->ActivityTaskManagerService.startActivity
frameworks/base/core/java/android/app/Instrumentation.java
Instrumentation是系統(tǒng)進(jìn)程和App進(jìn)程交互的監(jiān)測(cè)類,執(zhí)行execStartActivity
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
Uri referrer = target != null ? target.onProvideReferrer() : null;
try {
intent.migrateExtraStreamToClipData(who);
intent.prepareToLeaveProcess(who);
//通過binder機(jī)制,ActivityTaskManager.getService()獲取到了ActivityTaskManagerservice
int result = ActivityTaskManager.getService().startActivity(whoThread,
who.getBasePackageName(), who.getAttributionTag(), 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;
}
frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
ActivityTaskManagerService繼承了IActivityTaskManager.Stub,這里采用了AIDL的形式獲取到了ActivityTaskManagerService的代理類
,然后跨進(jìn)程通信ActivityTaskManagerService調(diào)用startActivity方法啟動(dòng)activity
public static IActivityTaskManager getService() {
return IActivityTaskManagerSingleton.get();
}
@UnsupportedAppUsage(trackingBug = 129726065)
private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
new Singleton<IActivityTaskManager>() {
@Override
protected IActivityTaskManager create() {
//通過 ServiceManager 獲取對(duì)應(yīng)的系統(tǒng)服務(wù),也就是 IBinder 類型的 ATMS 引用。
final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
return IActivityTaskManager.Stub.asInterface(b);
}
};
ActivityTaskManagerService extends IActivityTaskManager.Stub
總結(jié):startActivitySafely(Launcher)->startActivityForResult(Activity)->execStartActivity(Instrumentation)->startActivity(ATMS)