android启动拷贝system,android系统从SystemServer到Launcher的启动过程

android系统从SystemServer到Launcher的启动过程

android系统从init进程到SystemServer的启动过程请移驾,本文主要从流程的角度分析SystemServer如何启动的Launcher应用程序,不注重细节。

SystemServer

public static void main(String[] args) {

new SystemServer().run();

}

zygote进程通过反射启动SystemServer的main方法调用run方法。

private void run() {

try {

...

// 实例化SystemServiceManager.

mSystemServiceManager = new SystemServiceManager(mSystemContext);

mSystemServiceManager.setStartInfo(mRuntimeRestart,

mRuntimeStartElapsedTime, mRuntimeStartUptime);

LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

// Prepare the thread pool for init tasks that can be parallelized

SystemServerInitThreadPool.get();

} finally {

traceEnd(); // InitBeforeStartServices

}

// 启动关键服务.

try {

traceBeginAndSlog("StartServices");

//启动BootstrapServices

startBootstrapServices();

startCoreServices(); //启动一些核心服务

startOtherServices();

SystemServerInitThreadPool.shutdown();

} catch (Throwable ex) {

Slog.e("System", "******************************************");

Slog.e("System", "************ Failure starting system services", ex);

throw ex;

} finally {

traceEnd();

}

....

//启动系统Looper开始消息循环.

Looper.loop();

throw new RuntimeException("Main thread loop unexpectedly exited");

}

SystemServer里面加载android_servers的动态库 设置系统一些属性如时区、语言等 启动系统的服务如AMS、PMS、WMS等

具体启动服务的代码调用在下面三个方法中。

startBootstrapServices();

startCoreServices();

startOtherServices();

关于启动ams和系统UI方面主要在startOtherServices中

mActivityManagerService.systemReady(() -> {

Slog.i(TAG, "Making services ready");traceBeginAndSlog("StartActivityManagerReadyPhase");

....

traceBeginAndSlog("StartSystemUI");

try {

//启动SystemUI的关键代码

startSystemUi(context, windowManagerF);

} catch (Throwable e) {

reportWtf("starting System UI", e);

}

....

}, BOOT_TIMINGS_TRACE_LOG);

在SystemServer中调用ams的systemReady方法。

ActivityManagerService

systemReady关键代码如下

public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {

...

//回调SystemServer的方法启动SystemUI

if (goingCallback != null) goingCallback.run();

...

//启动activity

startHomeActivityLocked(currentUserId, "systemReady");

...

mStackSupervisor.resumeFocusedStackTopActivityLocked();

....

}

}

startHomeActivityLocked方法获取Launcher应用程序的intent并且通过系列方法启动。

boolean startHomeActivityLocked(int userId, String reason) {

if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL

&& mTopAction == null) {

return false;

}

//获取Launcher的Intent

Intent intent = getHomeIntent();

ActivityInfo aInfo = resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);

if (aInfo != null) {

intent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));

// Don't do this if the home app is currently being

// instrumented.

aInfo = new ActivityInfo(aInfo);

aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);

ProcessRecord app = getProcessRecordLocked(aInfo.processName,

aInfo.applicationInfo.uid, true);

if (app == null || app.instr == null) {

intent.setFlags(intent.getFlags() | FLAG_ACTIVITY_NEW_TASK);

final int resolvedUserId = UserHandle.getUserId(aInfo.applicationInfo.uid);

// For ANR debugging to verify if the user activity is the one that actually

// launched.

final String myReason = reason + ":" + userId + ":" + resolvedUserId;

//startHomeActivity

mActivityStartController.startHomeActivity(intent, aInfo, myReason);

}

} else {

Slog.wtf(TAG, "No home screen found for " + intent, new Throwable());

}

return true;

}

上述代码中获取到intent并调用ActivityStartController.startHomeActivity方法启动homeactivity

ActivityStartController

void startHomeActivity(Intent intent, ActivityInfo aInfo, String reason) {

mSupervisor.moveHomeStackTaskToTop(reason);

mLastHomeActivityStartResult = obtainStarter(intent, "startHomeActivity: " + reason)

.setOutActivity(tmpOutRecord)

.setCallingUid(0)

.setActivityInfo(aInfo)

.execute();

mLastHomeActivityStartRecord = tmpOutRecord[0];

if (mSupervisor.inResumeTopActivity) {

// If we are in resume section already, home activity will be initialized, but not

// resumed (to avoid recursive resume) and will stay that way until something pokes it

// again. We need to schedule another resume.

mSupervisor.scheduleResumeTopActivities();

}

}

obtainStarter方法通过工厂方法获取ActivityStarter,然后设置参数调用ActivityStarter的execute方法。

ActivityStarter

execute方法调用了startActivity方法

private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,

String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,

IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,

IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,

String callingPackage, int realCallingPid, int realCallingUid, int startFlags,

SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,

ActivityRecord[] outActivity, TaskRecord inTask, String reason,

boolean allowPendingRemoteAnimationRegistryLookup,

PendingIntentRecord originatingPendingIntent) {

if (TextUtils.isEmpty(reason)) {

throw new IllegalArgumentException("Need to specify a reason.");

}

mLastStartReason = reason;

mLastStartActivityTimeMs = System.currentTimeMillis();

mLastStartActivityRecord[0] = null;

//进到下一步启动

mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,

aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,

callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,

options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,

inTask, allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent);

if (outActivity != null) {

// mLastStartActivityRecord[0] is set in the call to startActivity above.

outActivity[0] = mLastStartActivityRecord[0];

}

return getExternalResult(mLastStartActivityResult);

}

startActivity方法调用了另一个startActivity方法

private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,

String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,

IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,

IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,

String callingPackage, int realCallingPid, int realCallingUid, int startFlags,

SafeActivityOptions options,

boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,

TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup,

PendingIntentRecord originatingPendingIntent) {

.....

//进入下步

return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,

true /* doResume */, checkedOptions, inTask, outActivity);

}

具体细节不做分析

private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,

IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,

int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,

ActivityRecord[] outActivity) {

int result = START_CANCELED;

...

mService.mWindowManager.deferSurfaceLayout();

//关键代码

result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,

startFlags, doResume, options, inTask, outActivity);

....

}

private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,

IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,

int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,

ActivityRecord[] outActivity) {

...

//关键代码1

mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,

mOptions);

...

//关键代码2

mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,

mOptions);

...

}

关键代码1出创建了新的task任务 关键代码2处进行下一步操作

ActivityStackSupervisor

boolean resumeFocusedStackTopActivityLocked(

ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {

if (!readyToResume()) {

return false;

}

if (targetStack != null && isFocusedStack(targetStack)) {

return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);

}

final ActivityRecord r = mFocusedStack.topRunningActivityLocked();

if (r == null || !r.isState(RESUMED)) {

//关键代码

mFocusedStack.resumeTopActivityUncheckedLocked(null, null);

} else if (r.isState(RESUMED)) {

// Kick off any lingering app transitions form the MoveTaskToFront operation.

mFocusedStack.executeAppTransition(targetOptions);

}

return false;

}

调用ActivityStack的resumeTopActivityUncheckedLocked

ActivityStack

boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {

if (mStackSupervisor.inResumeTopActivity) {

// Don't even start recursing.

return false;

}

boolean result = false;

try {

// Protect against recursion.

mStackSupervisor.inResumeTopActivity = true;

//关键代码

result = resumeTopActivityInnerLocked(prev, options);

final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);

if (next == null || !next.canTurnScreenOn()) {

checkReadyForSleep();

}

} finally {

mStackSupervisor.inResumeTopActivity = false;

}

return result;

}

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {

....

mStackSupervisor.startSpecificActivityLocked(next, true, true);

....

}

ActivitySrackSupervisor

void startSpecificActivityLocked(ActivityRecord r,

boolean andResume, boolean checkConfig) {

// Is this activity's application already running?

ProcessRecord app = mService.getProcessRecordLocked(r.processName,

r.info.applicationInfo.uid, true);

if (app != null && app.thread != null) {

try {

if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0

|| !"android".equals(r.info.packageName)) {

// Don't add this if it is a platform component that is marked

// to run in multiple processes, because this is actually

// part of the framework so doesn't make sense to track as a

// separate apk in the process.

app.addPackage(r.info.packageName, r.info.applicationInfo.longVersionCode,

mService.mProcessStats);

}

realStartActivityLocked(r, app, 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.

}

// 关键代码

mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,

"activity", r.intent.getComponent(), false, false, true);

}

调用ams的startProcessLocked

ActivityManagerServer

@GuardedBy("this")

private boolean startProcessLocked(String hostingType, String hostingNameStr, String entryPoint,

ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,

String seInfo, String requiredAbi, String instructionSet, String invokeWith,

long startTime) {

...

final ProcessStartResult startResult = startProcess(app.hostingType, entryPoint,

app, app.startUid, gids, runtimeFlags, mountExternal, app.seInfo,

requiredAbi, instructionSet, invokeWith, app.startTime);

handleProcessStartedLocked(app, startResult.pid, startResult.usingWrapper,

startSeq, false);

...

}

Progress

Process :start ()-->ZygoteProcess:start()-->startViaZygote()-->openZygoteSocketIfNeeded()--->ZygoteState:connect()-->zygote :main()-->zygoteServer:runSelectLoop()-->ZygoteConnection:processOneCommand()--->handleChildProc()--->ZtgoteInit: zygoteInit()--->RuntimeInit: applicationInit()这里会通过反射创建ActivityThread并调用main函数

ActivityThread

public static void main(String[] args) {

...

ActivityThread thread = new ActivityThread();

thread.attach(false, startSeq);

...

}

private void attach(boolean system, long startSeq) {

...

final IActivityManager mgr = ActivityManager.getService();

try {

mgr.attachApplication(mAppThread, startSeq);

} catch (RemoteException ex) {

throw ex.rethrowFromSystemServer();

}

...

}

调用ams的attachApplication方法

ActivityManagerServer

@Override

public final void attachApplication(IApplicationThread thread, long startSeq) {

synchronized (this) {

int callingPid = Binder.getCallingPid();

final int callingUid = Binder.getCallingUid();

final long origId = Binder.clearCallingIdentity();

//调用ActivityStackSupervisor的attachApplicationLocked方法并通过aidl创建Application

attachApplicationLocked(thread, callingPid, callingUid, startSeq);

Binder.restoreCallingIdentity(origId);

}

}

ActivityStackSupervisor

boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {

...

final ActivityRecord top = stack.topRunningActivityLocked();

final int size = mTmpActivityList.size();

for (int i = 0; i < size; i++) {

final ActivityRecord activity = mTmpActivityList.get(i);

if (activity.app == null && app.uid == activity.info.applicationInfo.uid

&& processName.equals(activity.processName)) {

try {

//关键代码

if (realStartActivityLocked(activity, app,

top == activity /* andResume */, true /* checkConfig */)) {

didSomething = true;

}

} catch (RemoteException e) {

Slog.w(TAG, "Exception in new application when starting activity "

+ top.intent.getComponent().flattenToShortString(), e);

throw e;

}

}

}

}

}

if (!didSomething) {

ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);

}

return didSomething;

}

final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,

boolean andResume, boolean checkConfig) throws RemoteException {

//调用ClientTransaction的schedule()

mService.getLifecycleManager().scheduleTransaction(clientTransaction);

}

调用ClientTransaction类中的schedule方法最终调用ActivityThread类中的内部类ApplicationThread的scheduleTransaction方法

ApplicationThread:scheduleTransaction()--> ClientTransactionHandler:scheduleTransaction()--->TransactionExecutor:execute(transaction)-->executeCallbacks()-->LaunchActivityItem:execute()-->

ActivityThread: handleLaunchActivity--->performLaunchActivity

时序图

9904cda5d1f7

image.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值