Android11系统之Launcher启动流程

Android11系统之Launcher启动流程,第1张

本文的内容主要是分析安卓系统源码,可能阅读起来会有点枯燥,所以最好可以跟着源码走一遍流程。

本文源码基于Android 11

Launcher 进程即 Android 系统桌面也是一个应用程序。随着 Android 系统不断更新,Launcher 也已经升级到现在的 Launcher3 了,本文主要研究 Launcher3 的启动过程。Launcher 作为一个应用程序由AMS(ActivityManagerService)来管理进程调度与启动,AMS是 Android 中最核心的系统服务,几乎所有的应用都需要与AMS通信。本文先从AMS启动入手,再分析由AMS启动 Launcher 的这个过程。

AMS的启动过程

从上篇文章安卓系统启动流程得知AMS是由 SystemServer 启动的,下面看看 SystemServer 内部执行流程

1.创建系统上下文

    private void createSystemContext() {
        ActivityThread activityThread = ActivityThread.systemMain();
        mSystemContext = activityThread.getSystemContext();
        mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);

        final Context systemUiContext = activityThread.getSystemUiContext();
        systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
    }

2.创建系统服务

// Create the system service manager.
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
        mRuntimeStartElapsedTime, mRuntimeStartUptime);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

3.startBootstrapServices()

引导服务中启动了ATMS(ActivityTaskManagerServici)、AMS等服务,其中ATMS是 Android 10中新增的,本来都是AMS来管理,可能考虑到AMS职责太多代码太庞大,所以单独拆出来ATMS用于管理Activity。

//创建ATMS和AMS
ActivityTaskManagerService atm = mSystemServiceManager.startService(
        ActivityTaskManagerService.Lifecycle.class).getService();
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
        mSystemServiceManager, atm);

ATMS和AMS内部都有一个 Lifecycle 用来创建并启动,publishBinderService 最后会调用到        ServiceManager.addService(),注册 Binder 服务。

//ActivityTaskManagerService内部类
public static final class Lifecycle extends SystemService {
   private final ActivityTaskManagerService mService;

   public Lifecycle(Context context) {
        super(context);
        mService = new ActivityTaskManagerService(context);
   }

   @Override
   public void onStart() {
       publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
       mService.start();
   }
}

4.startCoreServices 和 startOtherServices

startCoreServices 启动核心服务,基本都是系统的服务,startOtherServices启动其他服务,WMS就在这里启动。systemReady 方法会启动 Launcher 进程。

// 启动Launcher
mActivityManagerService.systemReady(() -> {
            mSystemServiceManager.startBootPhase(t, SystemService.PHASE_ACTIVITY_MANAGER_READY);
    startSystemUi(context, windowManagerF);
         
}

 SystemServer执行流程图:

Launcher启动流程

上文说到AMS的 systemReady 方法会启动 Launcher,来看看 Launcher 是如何被启动起来的。

ActivityManagerService.java
public void systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t) {
     ...
     mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
     ...
}

systemReady 中会调用 mAtmInternal.startHomeOnAllDisplays 方法,mAtmInternal 就是ActivityTaskManagerInternal,在ATMS的构造方法中初始化,是由ATMS对外提供的一个抽象类,真正的实现是在ATMS中的 LocalService,所以执行到了 LocalService 的 startHomeOnAllDisplays方法。

//ActivityTaskManagerService.java # LocalService
public boolean startHomeOnAllDisplays(int userId, String reason) {
    synchronized (mGlobalLock) {
        return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
    }
}

然后会调用到 startHomeOnTaskDisplayArea 方法,这里 getHomeIntent 方法中创建了一个 category为 CATEGORY_HOME 的 Intent,这个 category 会在 Launcher3 的 AndroidManifest.xml 中配置,表明是 HomeActivity,最后再调用 startHomeActivity 方法。

    boolean startHomeOnTaskDisplayArea(int userId, String reason, TaskDisplayArea taskDisplayArea,
            boolean allowInstrumenting, boolean fromHomeKey) {
        Intent homeIntent = null;
        ActivityInfo aInfo = null;

        homeIntent = mService.getHomeIntent();
        aInfo = resolveHomeActivity(userId, homeIntent);

        mService.getActivityStartController().startHomeActivity(homeIntent, aInfo, myReason,
                taskDisplayArea);
        return true;
    }

ActivityStartController.startHomeActivity

obtainStarter 方法返回的是 ActivityStarter 对象,它负责 Activity 的启动。这里多个 set 方法设置启动需要的参数, 最后 execute 方法才是真正的启动逻辑。这段代码看起来像构建者模式,实际上是工厂 + 享元 + 链式调用。

//ActivityStartController.java
void startHomeActivity(Intent intent, ActivityInfo aInfo, String reason,
            TaskDisplayArea taskDisplayArea) {
        //obtainStarter 返回一个 ActivityStarter,它负责 Activity 的启动
        mLastHomeActivityStartResult = obtainStarter(intent, "startHomeActivity: " + reason)
                .setOutActivity(tmpOutRecord)
                .setCallingUid(0)
                .setActivityInfo(aInfo)
                .setActivityOptions(options.toBundle())
                .execute();
    }

ActivityStarter.extcute 

onExecutionComplete 方法在 ActivityStartController 清除数据放回startPool池子中。

    int execute() {
        try {
            int res;
            synchronized (mService.mGlobalLock) {
                ...
                //执行这个方法
                res = executeRequest(mRequest);
                ...
        } finally {
            onExecutionComplete();
        }
    }

 ActivityStarter.executeRequest 

    private int executeRequest(Request request) {
        //调用 startActivityUnchecked
        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;
        try {
            //延时布局
            mService.deferWindowLayout();
            //执行startActivityInner
            result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants);
        } finally {
            //恢复布局
            mService.continueWindowLayout();
        }
        return result;
    }

 ActivityStarter.startActivityInner

int startActivityInner() { 
       if (mDoResume) {
            //ActivityRecord 记录着 Activity 信息
            final ActivityRecord topTaskActivity =
                    mStartActivity.getTask().topRunningActivityLocked();
            if (!mTargetStack.isTopActivityFocusable()
                    || (topTaskActivity != null && topTaskActivity.isTaskOverlay()
                    && mStartActivity != topTaskActivity)) {
                mTargetStack.getDisplay().mDisplayContent.executeAppTransition();
            } else {
                //执行resumeFocusedStacksTopActivities
                mRootWindowContainer.resumeFocusedStacksTopActivities(
                        mTargetStack, mStartActivity, mOptions);
            }
        }
        return START_SUCCESS;
    }

RootWindowContainer.resumeFocusedStacksTopActivities 

boolean resumeFocusedStacksTopActivities(
            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
        //如果是栈顶Activity,启动resumeTopActivityUncheckedLocked
        if (targetStack != null && (targetStack.isTopStackInDisplayArea()
                || getTopDisplayFocusedStack() == targetStack)) {
            result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
        }
        if (!resumedOnDisplay) {
            //获取栈顶的 ActivityRecord
            final ActivityStack focusedStack = display.getFocusedStack();
            if (focusedStack != null) {
                //执行resumeTopActivityUncheckedLocked
                result |= focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions);
            }
        }
      return result;
}

ActivityStack.resumeTopActivityUncheckedLocked

    boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
        boolean result = false;
        try {
            mInResumeTopActivity = true;
            //执行resumeTopActivityInnerLocked,
            //最终调用到ActivityStackSupervisor.startSpecificActivity
            result = resumeTopActivityInnerLocked(prev, options);
        } finally {
            mInResumeTopActivity = false;
        }
        return result;
    }

ActivityStackSupervisor.startSpecificActivity

这个方法是关键方法,如果进程已经存在直接执行 realStartActivityLocked 去启动 Activity,进程不存在则通过AMS去创建 Socket,然后通知 Zygote 去 fork 进程。由于这里第一次创建,所以走到 startProcessAsync

    void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
        // Is this activity's application already running?
        final WindowProcessController wpc =
                mService.getProcessController(r.processName, r.info.applicationInfo.uid);

        boolean knownToBeDead = false;
        //进程存在
        if (wpc != null && wpc.hasThread()) {
            try {
                //真正启动Activity方法
                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;
        }

        r.notifyUnknownVisibilityLaunchedForKeyguardTransition();

        final boolean isTop = andResume && r.isTopRunningActivity();
        //进程不存在 mService =ATMS
        mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
    }

以上流程调用栈如图

创建Socket建立连接

ActivityTaskManagerService.startProcessAsync

void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
            String hostingType) {
     //执行startProcess
     final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
                    mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
                    isTop, hostingType, activity.intent.getComponent());
     mH.sendMessage(m);
       
    }

调用 startProcessLocked,然后到 Process 的 start,最终到 ZygoteProcess 的attemptUsapSendArgsAndGetResult 通过 Socket 通信,fork 一个新的 Launcher 进程,调用过程如图

 ZygoteProcess.attemptZygoteSendArgsAndGetResult

通过 Socket 连接 Zygote 进程,把应用进程的一些参数写给前面连接的 zygote 进程

    private Process.ProcessStartResult attemptZygoteSendArgsAndGetResult(
            ZygoteState zygoteState, String msgStr) throws ZygoteStartFailedEx {
        try {
            final BufferedWriter zygoteWriter = zygoteState.mZygoteOutputWriter;
            final DataInputStream zygoteInputStream = zygoteState.mZygoteInputStream;

            zygoteWriter.write(msgStr);把应用进程的一些参数写给前面连接的zygote进程
            zygoteWriter.flush();//进入Zygote进程,处于阻塞状态
            //从socket中得到zygote创建的应用pid,赋值给 ProcessStartResult的对象
            Process.ProcessStartResult result = new Process.ProcessStartResult();
            result.pid = zygoteInputStream.readInt();
            result.usingWrapper = zygoteInputStream.readBoolean();
            return result;
        } catch (IOException ex) {
            zygoteState.close();
        }
    }
Zygote进程处理

ZygoteInit.main

public static void main(String argv[]) {
    Runnable caller;
    if (startSystemServer) {
        //Zygote Fork出的第一个进程 SystmeServer
        Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);
 
        if (r != null) {
            r.run();
            return;
        }
    }
    //循环等待fork出其他的应用进程,比如Launcher
    caller = zygoteServer.runSelectLoop(abiList);
    ...
    if (caller != null) {
        caller.run(); //执行runSelectLoop返回的Runnable对象,进入子进程
    }
}

ZygoteServer.runSelectLoop 

Runnable runSelectLoop(String abiList) {
    while (true) {
        int pollReturnValue;
            try {
                //epoll机制 循环
                pollReturnValue = Os.poll(pollFDs, pollTimeoutMs);
            } catch (ErrnoException ex) {
                throw new RuntimeException("poll failed", ex);
            }
            ...
            //来了消息后,调用processOneCommand()来进行进程的处理
            final Runnable command =  connection.processOneCommand(this);
    } 
}

ZygoteConnection.processOneCommand 

Runnable processOneCommand(ZygoteServer zygoteServer) {
            //fork进程,得到新进程pid
            //pid=0 表示Zygote  fork子进程成功
            //pid > 0 表示子进程 的真正的PID
            pid = Zygote.forkAndSpecialize(parsedArgs.mUid, parsedArgs.mGid, parsedArgs.mGids,
                parsedArgs.mRuntimeFlags, rlimits, parsedArgs.mMountExternal, parsedArgs.mSeInfo,
                parsedArgs.mNiceName, fdsToClose, fdsToIgnore, parsedArgs.mStartChildZygote,
                parsedArgs.mInstructionSet, parsedArgs.mAppDataDir, parsedArgs.mIsTopApp,
                parsedArgs.mPkgDataInfoList, parsedArgs.mWhitelistedDataInfoList,
                parsedArgs.mBindMountAppDataDirs, parsedArgs.mBindMountAppStorageDirs);
        try {
            //fork成功,第一次返回的pid = 0
            if (pid == 0) {
                return handleChildProc(parsedArgs, childPipeFd, parsedArgs.mStartChildZygote);
            } else {
                handleParentProc(pid, serverPipeFd);
                return null;
            }
}

 ZygoteConnection.handleChildProc

这里主要执行到 ZygoteInit.zygoteInit,zygoteInit 进行一些环境的初始化、启动Binder进程等 *** 作,最终反射执行 ActivityThread.main

    private Runnable handleChildProc(ZygoteArguments parsedArgs,
            FileDescriptor pipeFd, boolean isZygote) {
        closeSocket();
        Zygote.setAppProcessName(parsedArgs, TAG);
            if (!isZygote) {
                //App进程将会调用到这里,最终反射执行ActivityThread.main
                return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
                        parsedArgs.mDisabledCompatChanges,
                        parsedArgs.mRemainingArgs, null /* classLoader */);
            } else {
                return ZygoteInit.childZygoteInit(parsedArgs.mTargetSdkVersion,
                        parsedArgs.mRemainingArgs, null /* classLoader */);
            }
        
    }

Zygote进程调用栈如图 

ActivityThread中处理 

Zygote fork出了 Launcher 的进程,并把接下来的 Launcher 启动任务交给了 ActivityThread 来进行,接下来我们就从 ActivityThread.main方法来分析 Launcher 的创建过程。

ActivityThread.main

创建 ActivityThread 对象,调用 attach 进行处理,最终进入 Looper 循环

    public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
        //创建主线程Looper
        Looper.prepareMainLooper();
        ActivityThread thread = new ActivityThread();
        //执行attach
        thread.attach(false, startSeq);
        //开启循环
        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

 ActivityThread.attach

private void attach(boolean system, long startSeq) {
   
   RuntimeInit.setApplicationObject(mAppThread.asBinder());
   final IActivityManager mgr = ActivityManager.getService();
   try {
       //应用的句柄发给AMS,从而使AMS可以管理新进程
       mgr.attachApplication(mAppThread, startSeq);
   } catch (RemoteException ex) {
       throw ex.rethrowFromSystemServer();
   }

}

 ActivityManagerService.attachApplication

    public final void attachApplication(IApplicationThread thread, long startSeq) {
        if (thread == null) {
            throw new SecurityException("Invalid application interface");
        }
        synchronized (this) {
            //通过Binder获取传入的pid信息
            int callingPid = Binder.getCallingPid();
            final int callingUid = Binder.getCallingUid();
            final long origId = Binder.clearCallingIdentity();
            //执行attachApplicationLocked
            attachApplicationLocked(thread, callingPid, callingUid, startSeq);
            Binder.restoreCallingIdentity(origId);
        }
    }

ActivityManagerService.attachApplicationLocked

调用ATM的 attachApplication(),最终层层调用到 ActivityStackSupervisor 的 realStartActivityLocked,真正准备去启动Activity。

private final boolean attachApplicationLocked(IApplicationThread thread,
        int pid, int callingUid, long startSeq) {
    //如果当前的Application记录仍然依附到之前的进程中,则清理掉
    if (app.thread != null) {
        handleAppDiedLocked(app, true, true);
    }
    if (normalMode) {
      //调用ATM的attachApplication(),最终层层调用到ActivityStackSupervisor.java的 realStartActivityLocked()
      didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
    }
    return true;
}

 ActivityThread调用栈如图 

小结

至此已经走到 realStartActivityLocked,接下来就是 Activity 的启动流程,Activity 启动下篇文章会单独分析。总结一下 Launcher 启动流程,Launcher的启动经过了三个阶段:

1、SystemServer 创建AMS和ATMS,通过 SystemReady 进入 LauncherActivity 的调用

2、Zygote 进程 fork 出 Launcher 进程,通过 Socket 进行通信

3、进入 ActivityThread 的处理,完成 Launcher 的 Acitivty 启动

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/992330.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存