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);

}

ActivityTaskManager.java

public static IActivityTaskManager getService() {

return IActivityTaskManagerSingleton.get();

}

private static final Singleton IActivityTaskManagerSingleton =

new Singleton() {

@Override

protected IActivityTaskManager create() {

final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);

return IActivityTaskManager.Stub.asInterface(b);

}

}

};

这一步Launcher开始向AMS通信,由于在不同的进程所以需要通过Binder来通信,IActivityTaskManager是一个代理AMS端Binder的对象,之后AMS开始startActivity。 到这里Launcher向AMS请求启动一个Activity的流程就结束了。

2.AMS启动Activity并通知Launcher进入Paused状态

现在的流程是在AMS中,也就是另一个进程中,上一步通过代理调用到AMS的startActivity方法,接下来的调用如下:

ActivityTaskManagerService.java

@Override

public final int startActivity(IApplicationThread caller, String callingPackage,

String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,

String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,

Bundle bOptions) {

return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,

resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,

UserHandle.getCallingUserId());

}

@Override

public int startActivityAsUser(IApplicationThread caller, String callingPackage,

String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,

String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,

Bundle bOptions, int userId) {

return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,

resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,

true /validateIncomingUser/);

}

private int startActivityAsUser(IApplicationThread caller, String callingPackage,

@Nullable String callingFeatureId, Intent intent, String resolvedType,

IBinder resultTo, String resultWho, int requestCode, int startFlags,

ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {

userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,

Binder.getCallingPid(), Binder.getCallingUid(), “startActivityAsUser”);

return getActivityStartController().obtainStarter(intent, “startActivityAsUser”)

.setCaller(caller)

.setCallingPackage(callingPackage)

.setCallingFeatureId(callingFeatureId)

.setResolvedType(resolvedType)

.setResultTo(resultTo)

.setResultWho(resultWho)

.setRequestCode(requestCode)

.setStartFlags(startFlags)

.setProfilerInfo(profilerInfo)

.setActivityOptions(bOptions)

.setUserId(userId)

.execute();

}

ActivityStarter obtainStarter(Intent intent, String reason) {

return mFactory.obtain().setIntent(intent).setReason(reason);

}

上面几步主要是做权限检查

ActivityStarter.java

int execute() {

res = executeRequest(mRequest);

}

//层层调用会到下面这个方法

ActivityStack.java

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {

if (mResumedActivity != null) {

pausing |= startPausingLocked(userLeaving, false , next);

}

mStackSupervisor.startSpecificActivity(next, true, false);

}

startPausingLocked方法主要是通知Launcher进入Paused状态,在它进入这个状态后,在ActivityStackSupervisor.startSpecificActivity方法判断新的App进程状态做出不同响应,如下:

ActivityStackSupervisor.java

void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {

// 获取要启动的Activity进程信息

final WindowProcessController wpc =

mService.getProcessController(r.processName, r.info.applicationInfo.uid);

boolean knownToBeDead = false;

//如果进程存在且有进程中有线程存在 就是启动一个同应用的Activity(普通Activity就在此执行)

if (wpc != null && wpc.hasThread()) {

try {

realStartActivityLocked(r, wpc, andResume, checkConfig);

return;

} catch (RemoteException e) {

Slog.w(TAG, "Exception when starting activity "

  • r.intent.getComponent().flattenToShortString(), e);

}

// If a dead object exception was thrown – fall through to

// restart the application.

knownToBeDead = true;

}

//否则通过AMS向Zygote进程请求创建新的进程

r.notifyUnknownVisibilityLaunchedForKeyguardTransition();

final boolean isTop = andResume && r.isTopRunningActivity();

mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? “top-activity” : “activity”);

}

截止到这里完成了Launcher和AMS的通信,以及AMS和Zygote进程的通信,接下来我们要创建要启动的App的线程,即ActivityThread。

3.新的进程启动,ActivityThread的main函数入口

上一部分Zygote启动新的进程时标记ActivityThread.main函数,在Zygote创建好新进程后通过反射调用此方法,现在处于新App的进程中。

ActivityThread.java

public static void main(String[] args) {

Looper.prepareMainLooper();

ActivityThread thread = new ActivityThread();

thread.attach(false, startSeq);

Looper.loop();

}

private void attach(boolean system, long startSeq) {

final IActivityManager mgr = ActivityManager.getService();

try {

mgr.attachApplication(mAppThread, startSeq);

} catch (RemoteException ex) {

throw ex.rethrowFromSystemServer();

}

}

ActivityManagerService.java

private boolean attachApplicationLocked(@NonNull IApplicationThread thread,

int pid, int callingUid, long startSeq) {

thread.bindApplication(processName, appInfo, providerList,

instr2.mClass,

profilerInfo, instr2.mArguments,

instr2.mWatcher,

instr2.mUiAutomationConnection, testMode,

mBinderTransactionTrackingEnabled, enableTrackAllocation,

isRestrictedBackupMode || !normalMode, app.isPersistent(),

new Configuration(app.getWindowProcessController().getConfiguration()),

app.compat, getCommonServicesLocked(app.isolated),

mCoreSettingsObserver.getCoreSettingsLocked(),

buildSerial, autofillOptions, contentCaptureOptions,

app.mDisabledCompatChanges);

didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());

}

这里主要是创建了Looper和ActivityThread对象,然后将当前应用ApplicationThread注册到AMS中,ApplicationThread是ActivityThread的内部类实现了IApplicationThread.Stub用此对象可跨进程通信,上面的代码逻辑分两步,第一步,在AMS绑定ApplicationThread时,发送了一个H.BIND_APPLICATION的Message,在Handler中处理该消息时调用了Application的onCreate方法,第二步,在mAtmInternal的attachApplication层层调用到ActivityStackSupervisor.realStartActivityLocked方法,整体如下:

public final void bindApplication(String processName, ApplicationInfo appInfo,

ProviderInfoList providerList, ComponentName instrumentationName,

ProfilerInfo profilerInfo, Bundle instrumentationArgs,

IInstrumentationWatcher instrumentationWatcher,

IUiAutomationConnection instrumentationUiConnection, int debugMode,

boolean enableBinderTracking, boolean trackAllocation,

boolean isRestrictedBackupMode, boolean persistent, Configuration config,

CompatibilityInfo compatInfo, Map services, Bundle coreSettings,

String buildSerial, AutofillOptions autofillOptions,

ContentCaptureOptions contentCaptureOptions, long[] disabledCompatChanges) {

sendMessage(H.BIND_APPLICATION, data);

}

public void handleMessage(Message msg) {

switch (msg.what) {

case BIND_APPLICATION:

AppBindData data = (AppBindData)msg.obj;

handleBindApplication(data);

Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);

break;

}

}

private void handleBindApplication(AppBindData data) {

mInstrumentation.callApplicationOnCreate(app);

}

到这里为止,新的App线程已经启动并且绑定了Application。

4.创建Activity

ActivityStackSupervisor.java

boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,

boolean andResume, boolean checkConfig) throws RemoteException {

final ClientTransaction clientTransaction = ClientTransaction.obtain(

proc.getThread(), r.appToken);

final DisplayContent dc = r.getDisplay().mDisplayContent;

clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),

System.identityHashCode®, r.info,

mergedConfiguration.getGlobalConfiguration(),

mergedConfiguration.getOverrideConfiguration(), r.compat,

r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),

r.getSavedState(), r.getPersistentSavedState(), results, newIntents,

dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),

r.assistToken, r.createFixedRotationAdjustmentsIfNeeded()));

final ActivityLifecycleItem lifecycleItem;

if (andResume) {

lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());

} else {

lifecycleItem = PauseActivityItem.obtain();

}

clientTransaction.setLifecycleStateRequest(lifecycleItem);

//执行clientTransaction

mService.getLifecycleManager().scheduleTransaction(clientTransaction);

}

ClientTransaction管理了Activity的启动信息,由ClientLifecycleManager执行,scheduleTransaction方法中发送了EXECUTE_TRANSACTION的消息给ActivityThread的H类处理,然后执行TransactionExecutor.execute(),之后执行handleLaunchActivity方法,如下

void scheduleTransaction(ClientTransaction transaction) throws RemoteException {

final IApplicationThread client = transaction.getClient();

transaction.schedule();

}

public void schedule() throws RemoteException {

mClient.scheduleTransaction(this);

}

void scheduleTransaction(ClientTransaction transaction) {

transaction.preExecute(this);

sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

img

img

img

img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)

最后

只要是程序员,不管是Java还是Android,如果不去阅读源码,只看API文档,那就只是停留于皮毛,这对我们知识体系的建立和完备以及实战技术的提升都是不利的。

真正最能锻炼能力的便是直接去阅读源码,不仅限于阅读各大系统源码,还包括各种优秀的开源库。

腾讯、字节跳动、阿里、百度等BAT大厂 2019-2021面试真题解析

资料太多,全部展示会影响篇幅,暂时就先列举这些部分截图

《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门即可获取!

比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!**

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)

最后

只要是程序员,不管是Java还是Android,如果不去阅读源码,只看API文档,那就只是停留于皮毛,这对我们知识体系的建立和完备以及实战技术的提升都是不利的。

真正最能锻炼能力的便是直接去阅读源码,不仅限于阅读各大系统源码,还包括各种优秀的开源库。

[外链图片转存中…(img-sbpzYjf8-1712419957691)]

腾讯、字节跳动、阿里、百度等BAT大厂 2019-2021面试真题解析

[外链图片转存中…(img-agOUKmru-1712419957692)]

资料太多,全部展示会影响篇幅,暂时就先列举这些部分截图

《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门即可获取!
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐