// Note we want to go through this call for compatibility with
// applications that may have overridden the method.
// 因为 options == null 所以走到这儿
startActivityForResult(intent, -1);
}
}
Activity#startActivityForResult(Intent, int)
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
startActivityForResult(intent, requestCode, null);
}
调用 startActivityForResult 的重载方法
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
if (mParent == null) {
options = transferSpringboardActivityOptions(options);
// 关键来了
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) {
// If this start is requesting a result, we can avoid making
// the activity visible until the result is received. Setting
// this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
// activity hidden during this time, to avoid flickering.
// This can only be done when a result is requested because
// that guarantees we will get information back when the
// activity is finished, no matter what happens to it.
mStartedActivity = true;
}
cancelInputsAndStartExitTransition(options);
// TODO Consider clearing/flushing other event sources and events for child windows.
} else {
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
// Note we want to go through this method for compatibility with
// existing applications that may have overridden it.
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}
关键调用 mInstrumentation.execStartActivity
app 进程到 ATMS 进程
Instrumentation#execStartActivity
@UnsupportedAppUsage
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;
if (referrer != null) {
intent.putExtra(Intent.EXTRA_REFERRER, referrer);
}
if (mActivityMonitors != null) {
synchronized (mSync) {
final int N = mActivityMonitors.size();
for (int i=0; i
final ActivityMonitor am = mActivityMonitors.get(i);
ActivityResult result = null;
if (am.ignoreMatchingSpecificIntents()) {
result = am.onStartActivity(intent);
}
if (result != null) {
am.mHits++;
return result;
} else if (am.match(who, null, intent)) {
am.mHits++;
if (am.isBlocking()) {
return requestCode >= 0 ? am.getResult() : null;
}
break;
}
}
}
}
try {
intent.migrateExtraStreamToClipData(who);
intent.prepareToLeaveProcess(who);
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;
}
最终通过 ActivityTaskManager.getService() 获取ATMS的服务代理并调用 ATMS.startActivity 方法,这时从 app 的进程进入到 SystemServer 进程,发生了一次跨进程!
ATMS 到 ActivityThread
ActivityTaskManagerService#startActivity
@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());
}
ActivityTaskManagerService#startActivityAsUser
@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/);
}
ActivityTaskManagerService#startActivityAsUser
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) {
assertPackageMatchesCallingUid(callingPackage);
enforceNotIsolatedCaller(“startActivityAsUser”);
userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Binder.getCallingPid(), Binder.getCallingUid(), “startActivityAsUser”);
// TODO: Switch to user app stacks here.
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();
}
最后 return 的对象设置了那么多属性并在最后调用 excute() 执行。
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();
先看看 getActivityStartController() 是个啥
ActivityStartController getActivityStartController() {
return mActivityStartController;
}
getActivityStartController().obtainStarter(intent, “startActivityAsUser”)
ActivityStarter obtainStarter(Intent intent, String reason) {
return mFactory.obtain().setIntent(intent).setReason(reason);
}
mFactory.obtain() 使用工厂模式从 DefaultFactory 类的缓存池(最大缓存数量为3) 中取出 ActivityStarter 对象
getActivityStartController().obtainStarter(intent, “startActivityAsUser”)
.setCaller(caller)
setCaller(caller) caller 是 IApplicationThread 类型的对象,等于 ActivityStarter 里缓存了与 app 进程连接的桥梁,之后可以进行跨进程调用 app 进程。
ApplicationThread是ActivityThread内部类,继承自IApplicationThread.Stub,作为服务端接受AMS发出的请求并执行,ApplicationThread是ActivityThread与AMS连接的桥梁。
再看最后的 execute()
return getActivityStartController().obtainStarter(intent, “startActivityAsUser”)
.setCaller(caller)
…
.execute();
ActivityStarter#execute
int execute() {
try {
…
res = executeRequest(mRequest);
…
-
return getExternalResult(mRequest.waitResult == null ? res
- waitForResult(res, mLastStartActivityRecord));
} finally {
onExecutionComplete();
}
}
ActivityStarter#executeRequest
/**
*执行活动启动请求,开始启动活动的旅程。在这里
*首先执行几个初步检查。正常的活动启动流程将
*通过{@link#startActivityUnchecked}到{@link#startactivitynner}。
*/
private int executeRequest(Request request) {
…
// 在这里创建 ActivityRecord 对象,用于描述 Activity 信息
final ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
callingPackage, callingFeatureId, intent, resolvedType, aInfo,
mService.getGlobalConfiguration(), resultRecord, resultWho, requestCode,
request.componentSpecified, voiceSession != null, mSupervisor, checkedOptions,
sourceRecord);
…
mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,
request.voiceInteractor, startFlags, true /* doResume */, checkedOptions, inTask,
restrictedBgActivity, intentGrants);
…
return mLastStartActivityResult;
}
ActivityStarter#startActivityUnchecked
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, Task inTask,
boolean restrictedBgActivity, NeededUriGrants intentGrants) {
int result = START_CANCELED;
final ActivityStack startedActivityStack;
try {
mService.deferWindowLayout();
Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, “startActivityInner”);
// 关键
result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
startedActivityStack = handleStartResult(r, result);
mService.continueWindowLayout();
}
postStartActivityProcessing(r, result, startedActivityStack);
return result;
}
ActivityStarter#startActivityInner
int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, Task inTask,
boolean restrictedBgActivity, NeededUriGrants intentGrants) {
…
mRootWindowContainer.resumeFocusedStacksTopActivities(
mTargetStack, mStartActivity, mOptions);
…
return START_SUCCESS;
}
调用了RootWindowContainer#resumeFocusedStacksTopActivities
boolean resumeFocusedStacksTopActivities(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
…
result |= focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions);
…
return result;
}
调用 ActivityStack#resumeTopActivityUncheckedLocked
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
…
result = resumeTopActivityInnerLocked(prev, options);
…
return result;
}
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
…
//关键关键!!! 传入了 next.app.getThread() 返回的是 IApplication
final ClientTransaction transaction =
ClientTransaction.obtain(next.app.getThread(), next.appToken);
transaction.setLifecycleStateRequest(
ResumeActivityItem.obtain(next.app.getReportedProcState(),
dc.isNextTransitionForward()));
mAtmService.getLifecycleManager().scheduleTransaction(transaction);
…
return true;
}
mStackSupervisor.startSpecificActivity(next, true, true);
ActivityStackSupervisor#startSpecificActivity
void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
…
realStartActivityLocked(r, wpc, andResume, checkConfig);
…
}
ActivityStackSupervisor#realStartActivityLocked
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
boolean andResume, boolean checkConfig) throws RemoteException {
…
// Create activity launch transaction.
// 关键关键!!! 传入了 proc.getThread() 返回的是 IApplication
// 赋值给 ClientTransaction 的 mClient 对象
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,
// TODO: Have this take the merged configuration instead of separate global
// and override configs.
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()));
// Set desired final state.
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// Schedule transaction.
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
…
}
通过缓存池获取 ClientTransaction 类型的对象,并通过 mService.getLifecycleManager()调用 scheduleTransaction 方法开始执行任务
mService 是 ActivityTaskManagerService 类型的对象
ActivityTaskManagerService#getLifecycleManager
ClientLifecycleManager getLifecycleManager() {
return mLifecycleManager;
}
返回的 ClientLifecycleManager 类型对象,再看它的 scheduleTransaction 做了啥
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
final IApplicationThread client = transaction.getClient();
transaction.schedule();
if (!(client instanceof Binder)) {
// If client is not an instance of Binder - it’s a remote call and at this point it is
// safe to recycle the object. All objects used for local calls will be recycled after
// the transaction is executed on client in ActivityThread.
transaction.recycle();
}
}
调用了 ClientTransaction 的 schedule 方法,简单粗暴。。。
要我们回头看 ClientTransaction 的 schedule 是怎么执行的
ATMS 进程切回 app 进程
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
咦 又调用了 mClient 的 scheduleTransaction 。。。 额绕了一圈
又要回头看看 mClient 对象是啥了
在 ClientTransaction 中 mClient 是这样定义的
/** Target client. */
private IApplicationThread mClient;
IApplicationThread 对象 是与 app 进程沟通的桥梁!
刚刚在 调用 ActivityStack#resumeTopActivityUncheckedLocked 中将 IApplicationThread 传进 ClientTransaction 里了呢。
所以转了一圈 这个 ClientTransaction 对象会在 IApplicationThread 中调用,
同学们应该了解过 app 进程的 ApplicationThread 是 ActivityThread 内部类,并且实现了 IApplicationThread.Stub 。
mClient.scheduleTransaction(this); 实际上是 ApplicationThread#scheduleTransaction
这时候发生了跨进程:从 SystemServer 进程到 app 进程
ApplicationThread#scheduleTransaction
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
内部调用了 ActivityThread#scheduleTransaction
追代码发现 ActivityThread 并没有 scheduleTransaction 方法的具体实现,这时候需要看看 ActivityThread 的父类有没有
ActivityThread 继承了 ClientTransactionHandler
在 ClientTransactionHandler 中找到了 scheduleTransaction
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
调用 sendMessage 方法并且 what 的值为 ActivityThread.H.EXECUTE_TRANSACTION
ClientTransactionHandler#sendMessage
abstract void sendMessage(int what, Object obj);
sendMessage 是抽象方法,找找在 ActivityThread 的具体实现
ActivityThread#sendMessage
void sendMessage(int what, Object obj) {
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)
最后
Android学习是一条漫长的道路,我们要学习的东西不仅仅只有表面的 技术,还要深入底层,弄明白下面的 原理,只有这样,我们才能够提高自己的竞争力,在当今这个竞争激烈的世界里立足。
人生不可能一帆风顺,有高峰自然有低谷,要相信,那些打不倒我们的,终将使我们更强大,要做自己的摆渡人。
资源持续更新中,欢迎大家一起学习和探讨。
《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!
年进入阿里一直到现在。**
深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
[外链图片转存中…(img-zxQyds0a-1712536633400)]
[外链图片转存中…(img-KAMBbFtV-1712536633400)]
[外链图片转存中…(img-yo3GSxfz-1712536633401)]
[外链图片转存中…(img-0BA3cAEC-1712536633401)]
[外链图片转存中…(img-rXDkVjQ1-1712536633401)]
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)
最后
Android学习是一条漫长的道路,我们要学习的东西不仅仅只有表面的 技术,还要深入底层,弄明白下面的 原理,只有这样,我们才能够提高自己的竞争力,在当今这个竞争激烈的世界里立足。
人生不可能一帆风顺,有高峰自然有低谷,要相信,那些打不倒我们的,终将使我们更强大,要做自己的摆渡人。
资源持续更新中,欢迎大家一起学习和探讨。
《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!
还没有评论,来说两句吧...