Android13 Activity启动流程源码分析
基于 Android T(13) 相关源码:
frameworks/base/services/core/java/com/android/server/wm/ ActivityTaskManagerService.java ActivityStarter.java RootWindowContainer.java Task.java TaskFragment.java ActivityTaskSupervisor.java frameworks/base/core/java/android/app/ Activity.java Instrumentation.java IActivityTaskManager.java IActivityTaskManager.aidl IApplicationThread.aidl ClientTransactionHandler.java ActivityThread.java(包括内部类 ApplicationThread ) UiTranslationController.java
activity启动流程调用流向:
Activity.java
startActivity -> startActivityForResult
Instrumentation.java
-> execStartActivity
IActivityTaskManager.java IActivityTaskManager.aidl
-> IActivityTaskManager.Stub.asInterface( ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE)) . startActivity
.
.
. (old_app_process通过AIDL-> binder跨进程调用到system_process)
.
.
ActivityTaskManagerService.java (extends IActivityTaskManager.Stub)
-> startActivity -> startActivityAsUser -> getActivityStartController().obtainStarter(intent, "startActivityAsUser").execute();
【此处obtainStarter是从ActivityStarter的成员变量异步池中获取activitystater,此池子容量为3(刚刚,现在,即将),获取后为其赋值此次启动的关键参数,都放在成员变量mRequest中,Request是静态内部类】
ActivityStarter.java
-> execute
【如果 mRequest.activityInfo == null 那么 mRequest.resolveActivity(mSupervisor)进行解析;;如果action是关机或者重启,则通过ShutdownCheckPoints记录是谁干的】
【此处的 resolveActivity 函数内会创建新的intent以避免对客户端传来的intent对象修改,
并通过 supervisor.resolveIntent(intent... 对成员变量resolveInfo赋值(这里可以为特殊应用添加独特的resolve方法赋值resolveInfo,来跳转到特定应用如weixin、chooseActivity等)
通过 supervisor.resolveActivity(intent... 对成员变量activityInfo赋值】
-> executeRequest
【启动请求正式开始被处理,从mRequest中拿出各种参数为activitystater的成员变量赋值 如:
ActivityInfo aInfo = request.activityInfo;
ResolveInfo rInfo = request.resolveInfoActivity;
此时有一般性判断并log打印 if (err == ActivityManager.START_SUCCESS) {
Slog.i(TAG, "START u" + userId + " {" + intent.toShortString(true, true, true, false) + "} from uid " + callingUid);
}
ActivityTaskManager: START u0 {flg=0x40000 cmp=com.eg.android.AlipayGphone/com.alipay.mobile.nebulax.xriver.activity.XRiverActivity (has extras)} from uid 10074, pid 7992, result code=0(code为0是成功打开,2是已打开从后台调整到前台)
//如果进程已经存在,会打印 ActivityTaskManager: The Process com.tencent.news Already Exists in BG. So sending its PID: 11291
//enent.log会打印 am_proc_start ,可追溯追踪到进程创建、进程号、进程名 ; am_create_activity 可追溯启动的Activity,意图信息
ActivityRecord sourceRecord = ActivityRecord.isInAnyTask(resultTo);
ActivityRecord resultRecord = sourceRecord ;
并做一些判断如 boolean abort = !mSupervisor.checkStartAnyActivityPermission...(检查activity启动权限)
IntentFirewall.Result ifwResult = mService.mIntentFirewall.checkStartActivity(intent...(特殊的Intent检查)
boolean restrictedBgActivity = shouldAbortBackgroundActivityStart(...(检查是否为受限制的后台应用)
打印启动的Intent信息:(说明是谁启动了谁!)
IntentFirewall: CHECK INTENT - ComponentName[com.android.permissioncontroller/.permission.ui.sensitive.SensitivePermissionActivity], intentType[activity],
intent[com.android.permissioncontroller.SENSITIVE_PERMISSION], caller/callee[10065, 10160], callerPackage[com.android.systemui]
解析启动模式如 FLAG_ACTIVITY_NEW_TASK 】
【至此,已确认caller有必要的权限来启动activity,且大多数初步检查已完成】
【创建 final ActivityRecord r = new ActivityRecord.Builder(mService)
.setCaller(callerApp)
.setLaunchedFromPid(callingPid)
.setLaunchedFromUid(callingUid)
.setLaunchedFromPackage(callingPackage)
.setLaunchedFromFeature(callingFeatureId)
.setIntent(intent)
.setResolvedType(resolvedType)
.setActivityInfo(aInfo)
.setConfiguration(mService.getGlobalConfiguration())
.setResultTo(resultRecord)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setComponentSpecified(request.componentSpecified)
.setRootVoiceInteraction(voiceSession != null)
.setActivityOptions(checkedOptions)
.setSourceRecord(sourceRecord)
.build();
并会从 ProtoLog.v(WM_DEBUG_STATES, "State movement: %s from:%s to:%s reason:%s", this, getState(), state, reason); 打开 WM_DEBUG_STATES 即可收到如下log:
ActivityTaskManager: State movement: ActivityRecord{ed5f802 u0 com.android.deskclock/.DeskClock t-1} from:null to:INITIALIZING reason:ActivityRecord ctor 】
mRequest.logMessage.append(" result code=").append(res);会打印result code,0为成功打开,2为已打开从后台调到前台。
-> startActivityUnchecked
-> startActivityInner
若startActivity从非Activity调用,在这种情况下,我们总是启动一个新任务, 通过调用computeLaunchingTaskFlags()在此函数中打印
Slog.w(TAG, "startActivity called from non-Activity context; forcing " + "Intent.FLAG_ACTIVITY_NEW_TASK for: " + mIntent);}
如: ActivityTaskManager: startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { flg=0x40000
cmp=com.eg.android.AlipayGphone/com.alipay.mobile.nebulax.xriver.activity.XRiverActivity (has extras)}
【check mLaunchFlags 并以launch的方式处理栈,将其加入到正确的栈中。检查要启动的activity是否就是当前activity以及是否要重复拉起】
startActivityLocked:
ProtoLog.i(WM_DEBUG_ADD_REMOVE, "Adding activity %s to task %s " 5080 + "callers: %s", r, task, new RuntimeException("here").fillInStackTrace());
处理Intent.FLAG_ACTIVITY_NO_ANIMATION、FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
-> resumeFocusedTasksTopActivities
RootWindowContainer.java
-> resumeFocusedTasksTopActivities
【getFocusedRootTask()!=null 即确保当前焦点所在的活动根栈不为空时(确保不是设备刚启动或者launcher刚崩溃)对target执行下一步启动resumeTopActivityUncheckedLocked,
否则先resumeHomeActivity 以保证home activity至少已启动,再尝试resumeTopActivityUncheckedLocked。如果连resumeHomeActivity都失败就会停止启动target】
Task.java
-> resumeTopActivityUncheckedLocked
【确保根栈中的顶部的首个可以被focused的activity被resumed】
-> resumeTopActivityInnerLocked
【考虑根栈为空的情况,是否换栈或启动home activity】
TaskFragment.java
-> resumeTopActivity (很长)
【If the top activity is the resumed one, nothing to do.】
【The next activity is already visible, so hide the previous activity windows right now】
【next.attachedToProcess()】
【next.setVisibility(true);This activity is now becoming visible.】
【next.setState(RESUMED, "resumeTopActivity");】
【mAtmService.getLifecycleManager().scheduleTransaction(transaction);同步生命周期状态】
ActivityTaskSupervisor.java
-> startSpecificActivity
【如果要启动的Activity进程已经创建,执行realStartActivityLocked方法
否则最后会调用 mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? HostingRecord.HOSTING_TYPE_TOP_ACTIVITY : HostingRecord.HOSTING_TYPE_ACTIVITY);来异步创建进程
并打印log(包括进程号): D Zygote : Forked child process 4888
ActivityManager: Start proc 4888:com.android.deskclock/u0a93 for activity {com.android.deskclock/com.android.deskclock.DeskClock}】
A:(要启动的Activity进程已经创建)
-> realStartActivityLocked
【mService.getLifecycleManager().scheduleTransaction(clientTransaction);同步生命周期状态】
IApplicationThread.aidl
-> scheduleTransaction
.
.
. (system_process通过AIDL-> binder跨进程调用到new_app_process)
. (每次scheduleTransaction都会引发生命周期状态的同步,举例resumed的同步如下)
.
private class ApplicationThread (extends IApplicationThread.Stub) in ActivityThread.java
-> scheduleTransaction
(ActivityThread extends) ClientTransactionHandler.java
-> scheduleTransaction
ActivityThread.java
-> sendMessage(H.UPDATE_UI_TRANSLATION_STATE, args)
H (in ActivityThread)
匹配case处理 :
Activity.java
-> updateUiTranslationState
UiTranslationController.java
-> updateUiTranslationState ( 这里做具体的Update the Ui translation state. 并打印log onAutoTranslationStateChange(): unknown state:)
B:(目标app进程尚未创建)
ActivityManagerService.java
->startProcessAsync
ProcessList.java
->handleProcessStartedLocked
.
. (创建完成后socket通信给新进程)
.
IApplicationThread.aidl
->bindApplication
ActivityThread.java
->bindApplication->sendMessage(H.BIND_APPLICATION, data)
->handleBindApplication(AppBindDatadata)
IActivityManager.aidl
->finishAttachApplication
.
. (新进程aidl通信给system_server进行attachApplication)
.
ActivityManagerService.java extends IActivityManager.Stub
->finishAttachApplication
->attachApplication
RootWindowContainer.java
->attachApplication
< 从lancher启动activity的Log流程,可以详见一篇博文 https://blog.csdn.net/weixin_42695485/article/details/108632021 >
以下为 Android 13 的代码细节流程:
☝
package android.app; ---frameworks/base/core/java/android/app/
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
package com.android.server.wm; ---frameworks/base/services/core/java/com/android/server/wm/
👇
☝
package com.android.server.wm; ---frameworks/base/services/core/java/com/android/server/wm/
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
package android.app; ---frameworks/base/core/java/android/app/
👇
原创博文,如有借阅请注明本文链接,感谢阅读
本文来自博客园,作者:小汀,转载请注明原文链接:https://www.cnblogs.com/1118zjg/p/16890178.html