前置知識
當(dāng)Android系統(tǒng)啟動時,首先會創(chuàng)建Zygote進程,Zygote進程啟動后會fork若干其他的進程摹蘑,例如SystemServer進程,Launcher進程轧飞。
創(chuàng)建SystemServer進程后會創(chuàng)建SystemServiceManager衅鹿,啟動很多系統(tǒng)服務(wù),例ActivityTaskManagerService踪少,ActivityManagerService恢着,PackageManagerService等源哩。
其中Launcher桌面實際上就是一個Activity,當(dāng)我們點擊桌面icon,也是通過startActivity來啟動App的磅崭。
在桌面點擊一個APP圖標(biāo)啟動APP的過程中譬涡,涉及到了跨進程通信合呐,APP進程創(chuàng)建板乙,Application和Activity的創(chuàng)建和啟動等內(nèi)容。
本篇文章主要分析點擊桌面App圖標(biāo)到ActivityTaskManagerService的過程具篇。
涉及到的幾個類
- 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是一個Activity纬霞,加載的布局為R.layout.launcher
- launcher.xml中的
layout="@layout/all_apps"
引入了LauncherAllAppsContainerView
,其中layout="@layout/all_apps_rv_layout"
引入了AllAppsRecyclerView
- 在AllAppsContainerView中為其設(shè)置的adapter是AllAppsGridAdapter驱显,點擊事件由launcher.getItemOnClickListener()獲取诗芜,通過ItemClickHandler.INSTANCE單例方法獲取點擊事件
- 最終調(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) {
//點擊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) {
//點擊Shortcut啟動activity
// Shortcuts need some special checks due to legacy reasons.
startShortcutIntentSafely(intent, optsBundle, item, sourceContainer);
} else if (user == null || user.equals(Process.myUserHandle())) {
//點擊app圖標(biāo)啟動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啟動activity
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
startActivityForResult(intent, -1);
}
}
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) {
//此時需要啟動的Activity的parent還是null
if (mParent == null) {
options = transferSpringboardActivityOptions(options);
//Instrumentation執(zhí)行了execStartActivity方法
//mMainThread:Launcher所在的進程
//mMainThread.getApplicationThread():獲取mMainThread.getApplicationThread(),ApplicationThread 繼承自 Stub埃疫,也就是 Binder伏恐,用于進程間通信
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)進程和App進程交互的監(jiān)測類,執(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機制栓霜,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的代理類
,然后跨進程通信ActivityTaskManagerService調(diào)用startActivity方法啟動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 獲取對應(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)