精华内容
下载资源
问答
  • AMS:ActivityManagerService是Android中的一个重要的服务,可以调度Activity和Service的生命周期,启动或者杀死app的进程等作用。 Activity系统的启动流程启动SystemService前,会启动Binder线程池,这样的话...

    AMS:ActivityManagerService是Android中的一个重要的服务,可以调度Activity和Service的生命周期,启动或者杀死app的进程等作用。

    在这里插入图片描述Activity系统的启动流程
    在这里插入图片描述
    在启动SystemService前,会启动Binder线程池,这样的话SystemService启动好了后,可以与Zygote孵化器跨进程通信。
    Launch应用程序:是用来显示系统中已经安装的App图标,是启动根Activity的入口。

    init进程启动

    启动内容主要有:Linux内核,init进程,Zygote进程,SystemServer进程,Launcher等

    AMS

    在这里插入图片描述

    App程序的启动

    在这里插入图片描述

    Activity启动

    在这里插入图片描述
    普通的Activity的启动就比根Activity启动少了第一步launcher程序向AMS发送消息;这里只是大概的步骤,其实每个步骤之间还有很多详细的地方没有画出来,中间有很多调用。

    Service启动

    在这里插入图片描述

    展开全文
  • Android Q中,activity的调度和管理已经从AMS移到了ActivityTaskManagerService中(这里简称ATMS) 简介 Launcher点击应用图标:这个过程是Launcher进程中进行的,去启动应用的第一个activity。 通过binder进入...

    前言

    在Android Q中,activity的调度和管理已经从AMS移到了ActivityTaskManagerService中(这里简称ATMS)

    简介

    1. Launcher点击应用图标:这个过程是Launcher进程中进行的,去启动应用的第一个activity。
    2. 通过binder进入ATMS:在ATMS中,为应用的第一个activity创建了ActivityRecord,找到其ActivityStack,将ActivityRecord插入到所在的TaskRecord的合适位置。最后执行到ActivityManagerInternal::startProcess
    3. 进入AMS,请求创建应用进程:这个过程创建了ProcessRecord对象并处理保存了进程所需的各种信息。最后通过Process.start()请求创建应用进程。
    4. Zygote创建应用进程:通过socket与zygote进程通信,fork出应用进程。
    5. 应用进程主线程-执行ActivityThread的main():在应用主线程中,执行ActivityThread的main()。
    6. 进入系统进程,绑定应用进程:创建了应用的Application,将应用进程绑定到ATMS中,由它们管理。
    7. 回到应用进程:这里主要是创建出应用第一个Activity,并执行了attach()和onCreate()。

    注:AMS和ATMS服务都是在系统进程-system server进程中。
    所以,整个过程 进程变化是:Launcher进程(binder)->systemserver进程(socket)->zygote进程(socket)->应用进程(binder)->systemserver进程(binder)->应用进程。
     

    Activity的启动过程详述

    ams_app_launcher

    桌面Launcher点击应用图标

    Launcher点击图标,BaseDraggingActivity.java中startActivitySafely()调用了startActivity()。
    这是的activity是Launcher的activity,在Launcher的进程中。

    Activity中各种startActivity()调用,最终都是走到的startActivityForResult(@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options)方法的。

    //Activity.java:
    @Override
    public void startActivity(Intent intent) {
        this.startActivity(intent, null);
    }
    
    @Override
    public void startActivity(Intent intent, @Nullable Bundle options) {
        if (options != null) {
            startActivityForResult(intent, -1, options);
        } else {
            // Note we want to go through this call for compatibility with
            // applications that may have overridden the method.
            startActivityForResult(intent, -1);
        }
    }
    
    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
        startActivityForResult(intent, requestCode, null);
    }
    

    所以Launcher点击图标后这里直接从startActivityForResult()开始看,从上面可以看到requestCode值为-1

    //Activity.java:
    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
        //mParent一般为null
        if (mParent == null) {
            options = transferSpringboardActivityOptions(options);
            //调用mInstrumentation.execStartActivity()
            //mMainThread、mInstrumentation、mToken在attach()被赋值
            Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);
            ......
        } else {
            //调用mParent.startActivityFromChild(),和上面逻辑类似
        }
    }
    

    目前还是在Launcher进程,这里mMainThread、mInstrumentation、mToken都是在attach()被赋值。
    Instrumentation监控system(主要是AM,Activity Manager)与application之间的所有交互。
    mToken是IBinder对象,是Binder代理,是Android中IPC重要部分。
    mMainThread是ActivityThread对象,应用的主线程。这里是Launhcer的主线程。
    那么什么时候被赋值的呢?attach()在哪被调用的?看到最后就知道了^v^

    这里关键代码 调用了mInstrumentation.execStartActivity()

    //Instrumentation.java
    @UnsupportedAppUsage
    public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
        IApplicationThread whoThread = (IApplicationThread) contextThread;
        ......
        try {
            intent.migrateExtraStreamToClipData();
            intent.prepareToLeaveProcess(who);
            int result = ActivityTaskManager.getService()
                .startActivity(whoThread, who.getBasePackageName(), 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().startActivity()这个方法。
    ActivityTaskManager.getService()这个涉及Binder机制,可以参考 Binder机制 。 这里获取的服务名是Context.ACTIVITY_TASK_SERVICE(=activity_task),最终调用的是ActivityTaskManagerService.startActivity()方法。
     

    进入ATMS

    通过Binder机制,由Launcher进程进入到ATMS。
    ActivityTaskManagerService中的startActivity()

    //ActivityTaskManagerService.java:
    @Override
    public final int startActivity(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                resultWho, requestCode, startFlags, profilerInfo, bOptions,
                UserHandle.getCallingUserId());
    }
    
        @Override
    public int startActivityAsUser(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
                true /*validateIncomingUser*/);
    }
    
    int startActivityAsUser(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
            boolean validateIncomingUser) {
        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)
                .setResolvedType(resolvedType)
                .setResultTo(resultTo)
                .setResultWho(resultWho)
                .setRequestCode(requestCode)
                .setStartFlags(startFlags)
                .setProfilerInfo(profilerInfo)
                .setActivityOptions(bOptions)
                .setMayWait(userId)
                .execute();
    
    }
    

    ATMS中的startActivity(),最终调用了ActivityStarter中的execute()。

    //ActivityStarter.java:
    ActivityStarter setMayWait(int userId) {
        mRequest.mayWait = true;
        mRequest.userId = userId;
        return this;
    }
    
    int execute() {
        try {
            // TODO(b/64750076): Look into passing request directly to these methods to allow
            // for transactional diffs and preprocessing.
            if (mRequest.mayWait) {
                return startActivityMayWait(mRequest.caller, mRequest.callingUid,
                        mRequest.callingPackage, mRequest.realCallingPid, mRequest.realCallingUid,
                        mRequest.intent, mRequest.resolvedType,
                        mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                        mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
                        mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
                        mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
                        mRequest.inTask, mRequest.reason,
                        mRequest.allowPendingRemoteAnimationRegistryLookup,
                        mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
            } else {
                ......
            }
        } finally {
            onExecutionComplete();
        }
    }
    

    在setMayWait()中,mRequest.mayWait = true;,因此走到startActivityMayWait()。

    //ActivityStarter.java:
    private int startActivityMayWait(IApplicationThread caller, int callingUid,
            String callingPackage, int requestRealCallingPid, int requestRealCallingUid,
            Intent intent, String resolvedType, IVoiceInteractionSession voiceSession,
            IVoiceInteractor voiceInteractor, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, WaitResult outResult,
            Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,
            int userId, TaskRecord inTask, String reason,
            boolean allowPendingRemoteAnimationRegistryLookup,
            PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
        ......
        ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
        synchronized (mService.mGlobalLock) {
            final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
            ......
            final ActivityRecord[] outRecord = new ActivityRecord[1];
            int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
                    voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
                    callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
                    ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
                    allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent,
                    allowBackgroundActivityStart);
            ......
            mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outRecord[0]);
            if (outResult != null) {
                outResult.result = res;
                final ActivityRecord r = outRecord[0];
                ......
            }
            return res;
        }
    }
    
    //startActivity 1
    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, boolean allowBackgroundActivityStart) {
    
        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,
                allowBackgroundActivityStart);
    
        if (outActivity != null) {
            // mLastStartActivityRecord[0] is set in the call to startActivity above.
            outActivity[0] = mLastStartActivityRecord[0];
        }
    
        return getExternalResult(mLastStartActivityResult);
    }
    
    //startActivity 2
    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, boolean allowBackgroundActivityStart) {
        .......
        ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
                callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
                resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
                mSupervisor, checkedOptions, sourceRecord);
        if (outActivity != null) {
            outActivity[0] = r;
        }
        ......
        final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
        ......
        final int res = startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
                true /* doResume */, checkedOptions, inTask, outActivity, restrictedBgActivity);
        mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outActivity[0]);
        return res;
    }
    

    这里主要的代码关注:startActivityMayWait()->startActivity()->startActivity()->startActivity()
    这里3个startActivity()的同名方法,参数是不一样的。参数很多得注意点看。 这几个方法内容都很多,这里主要注意几个地方:

    • ActivityRecord在对应一个activity,是activity的信息记录管理的类。这在 AMS之AMS的启动 都是提到过的。
    • startActivityMayWait()方法中new的ActivityRecord对象 outRecord[0],在第二个startActivity()中被赋值,指向的创建的ActivityRecord对象r。

    -----这里在第二个startActivity()中创建了应用第一个activity的ActivityRecord对象

    第二个startActivity()同样调用了startActivity(),也是ActivityStarter最后一个同名startActivity方法,这里标记为第三个startActivity()。

    //ActivityStarter.java:
    //第三个:startActivity 3
    private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
                ActivityRecord[] outActivity, boolean restrictedBgActivity) {
        int result = START_CANCELED;
        final ActivityStack startedActivityStack;
        try {
            mService.mWindowManager.deferSurfaceLayout();
            result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
        } finally {
            final ActivityStack currentStack = r.getActivityStack();
            startedActivityStack = currentStack != null ? currentStack : mTargetStack;
            ......      
        }
        ......
        return result;
    }
    

    第三个startActivity()中获取Activity所在的ActivityStack - startedActivityStack。

    这里看下startActivityUnchecked()。

    //ActivityStarter.java:
    // Note: This method should only be called from {@link startActivity}.
    private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity, boolean restrictedBgActivity) {
        ......
        mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,
                mOptions);
        if (mDoResume) {
            final ActivityRecord topTaskActivity =
                    mStartActivity.getTaskRecord().topRunningActivityLocked();
            if (!mTargetStack.isFocusable()
                    || (topTaskActivity != null && topTaskActivity.mTaskOverlay
                    && mStartActivity != topTaskActivity)) {
                // If the activity is not focusable, we can't resume it, but still would like to
                // make sure it becomes visible as it starts (this will also trigger entry
                // animation). An example of this are PIP activities.
                // Also, we don't want to resume activities in a task that currently has an overlay
                // as the starting activity just needs to be in the visible paused state until the
                // over is removed.
                mTargetStack.ensureActivitiesVisibleLocked(mStartActivity, 0, !PRESERVE_WINDOWS);
                // Go ahead and tell window manager to execute app transition for this activity
                // since the app transition will not be triggered through the resume channel.
                mTargetStack.getDisplay().mDisplayContent.executeAppTransition();
            } else {
                // If the target stack was not previously focusable (previous top running activity
                // on that stack was not visible) then any prior calls to move the stack to the
                // will not update the focused stack.  If starting the new activity now allows the
                // task stack to be focusable, then ensure that we now update the focused stack
                // accordingly.
                if (mTargetStack.isFocusable()
                        && !mRootActivityContainer.isTopDisplayFocusedStack(mTargetStack)) {
                    mTargetStack.moveToFront("startActivityUnchecked");
                }
                mRootActivityContainer.resumeFocusedStacksTopActivities(
                        mTargetStack, mStartActivity, mOptions);
            }
        } else if (mStartActivity != null) {
            mSupervisor.mRecentTasks.add(mStartActivity.getTaskRecord());
        }
        mRootActivityContainer.updateUserStack(mStartActivity.mUserId, mTargetStack);
    
        mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTaskRecord(),
                preferredWindowingMode, mPreferredDisplayId, mTargetStack);
    
        return START_SUCCESS;
    }
    
    • startActivityUnchecked()找到目标ActivityStack - mTargetStack,然后调用了mTargetStack.startActivityLocked()找到所在TaskRecord,并将activity插入到合适位置。 这样activity对应ActivityRecord就加入到对应ActivityStack中的对应的TaskRecord中了。
    • mRootActivityContainer.resumeFocusedStacksTopActivities();获取栈顶activity并恢复,即将设置成resume状态。

    这里看下这两个方法
    1. startActivityLocked()

    //ActivityStack.java:
    void startActivityLocked(ActivityRecord r, ActivityRecord focusedTopActivity,
            boolean newTask, boolean keepCurTransition, ActivityOptions options) {
        TaskRecord rTask = r.getTaskRecord();
        final int taskId = rTask.taskId;
        final boolean allowMoveToFront = options == null || !options.getAvoidMoveToFront();
        // mLaunchTaskBehind tasks get placed at the back of the task stack.
        if (!r.mLaunchTaskBehind && allowMoveToFront
                && (taskForIdLocked(taskId) == null || newTask)) {
            // Last activity in task had been removed or ActivityManagerService is reusing task.
            // Insert or replace.
            // Might not even be in.
            insertTaskAtTop(rTask, r);
        }
        TaskRecord task = null;
        ......
        task = activityTask;
        ......
        task.setFrontOfTask();
    
        // The transition animation and starting window are not needed if {@code allowMoveToFront}
        // is false, because the activity won't be visible.
        if ((!isHomeOrRecentsStack() || numActivities() > 0) && allowMoveToFront) {
            ......
        } else {
            // If this is the first activity, don't do any fancy animations,
            // because there is nothing for it to animate on top of.
            ActivityOptions.abort(options);
        }
    }
    

    这里找到activity的TaskRecord,并将activity对应的ActivityRecord插入到TaskRecord的合适位置。然后进行过渡动画相关判断处理。

    -----到此,应用第一个activity的ActivityRecord已创建,并找到其ActivityStack。最后在ActivityStack中将ActivityRecord插入到所在的TaskRecord的合适位置。
    参考 AMS之AMS的启动 最后面那个图理解下,ActivityStack、ActivityStackSupervisor、TaskRecord、ActivityRecord、ProcessRecord之间的关系。

    2.resumeFocusedStacksTopActivities()

    /**
     * Root node for activity containers.
     * TODO: This class is mostly temporary to separate things out of ActivityStackSupervisor.java. The
     * intention is to have this merged with RootWindowContainer.java as part of unifying the hierarchy.
     */
    //RootActivityContainer.java:
    boolean resumeFocusedStacksTopActivities(
            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
    
        if (!mStackSupervisor.readyToResume()) {
            return false;
        }
    
        boolean result = false;
        if (targetStack != null && (targetStack.isTopStackOnDisplay()
                || getTopDisplayFocusedStack() == targetStack)) {
            result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
        }
        ......
        return result;
    }
    

    这里看targetStack.resumeTopActivityUncheckedLocked()

    //ActivityStack.java:
    @GuardedBy("mService")
    boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
        if (mInResumeTopActivity) {
            // Don't even start recursing.
            return false;
        }
    
        boolean result = false;
        try {
            // Protect against recursion.
            mInResumeTopActivity = true;
            result = resumeTopActivityInnerLocked(prev, options);
    
            // When resuming the top activity, it may be necessary to pause the top activity (for
            // example, returning to the lock screen. We suppress the normal pause logic in
            // {@link #resumeTopActivityUncheckedLocked}, since the top activity is resumed at the
            // end. We call the {@link ActivityStackSupervisor#checkReadyForSleepLocked} again here
            // to ensure any necessary pause logic occurs. In the case where the Activity will be
            // shown regardless of the lock screen, the call to
            // {@link ActivityStackSupervisor#checkReadyForSleepLocked} is skipped.
            final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
            if (next == null || !next.canTurnScreenOn()) {
                checkReadyForSleep();
            }
        } finally {
            mInResumeTopActivity = false;
        }
    
        return result;
    }
    
    //ActivityStack.java:
    @GuardedBy("mService")
    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
        // Find the next top-most activity to resume in this stack that is not finishing and is
        // focusable. If it is not focusable, we will fall into the case below to resume the
        // top activity in the next focusable task.
        ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
        ......
        boolean pausing = getDisplay().pauseBackStacks(userLeaving, next, false);
        if (mResumedActivity != null) {
            pausing |= startPausingLocked(userLeaving, false, next, false);
        }
        ......
        if (next.attachedToProcess()) {
            ......
        } else {
            ......
            mStackSupervisor.startSpecificActivityLocked(next, true, true);
        }
    
        return true;
    }
    

    由于activity所在应用的进程还未生成,此时next.attachedToProcess()明显是false的。直接看mStackSupervisor.startSpecificActivityLocked(next, true, true);

    //ActivityStackSupervisor.java:
    void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
        // Is this activity's application already running?
        final WindowProcessController wpc =
                mService.getProcessController(r.processName, r.info.applicationInfo.uid);
        if (wpc != null && wpc.hasThread()) {
            try {
                realStartActivityLocked(r, wpc, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
            }
        }
        ......
        try {
            if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
                Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
                        + r.processName);
            }
            // Post message to start process to avoid possible deadlock of calling into AMS with the
            // ATMS lock held.
            final Message msg = PooledLambda.obtainMessage(
                    ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
                    r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
            mService.mH.sendMessage(msg);
        } finally {
            Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
        }
    }
    

    如果已有进程会走realStartActivityLocked()。 这里走startProcess(),这里的mService即ActivityTaskManagerService(ATMS),mService.mH是ATMS的内部类 自定义的Handler。
    关于这个Handler:它是ATMS initialize()时创建的,它的Looper是AMS中mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController, DisplayThread.get().getLooper());传入的,即DisplayThread.get().getLooper()。这个DisplayThread比较特别,可以看下注释。
    Hanler相关可以参考下消息机制
    接着直接查看ActivityManagerInternal::startProcess。

    /**
     * Shared singleton foreground thread for the system.  This is a thread for
     * operations that affect what's on the display, which needs to have a minimum
     * of latency.  This thread should pretty much only be used by the WindowManager,
     * DisplayManager, and InputManager to perform quick operations in real time.
     */
    public final class DisplayThread extends ServiceThread {
        private DisplayThread() {
            // DisplayThread runs important stuff, but these are not as important as things running in
            // AnimationThread. Thus, set the priority to one lower.
            super("android.display", Process.THREAD_PRIORITY_DISPLAY + 1, false /*allowIo*/);
        }
    

    ActivityManagerInternal::startProcess,ActivityManagerInternal是抽象类,实现是AMS中的内部类LocalService。
     

    进入AMS,请求创建应用进程

    这里直接看startProcess。

    //ActivityManagerService.java:
    @Override
    public void startProcess(String processName, ApplicationInfo info,
            boolean knownToBeDead, String hostingType, ComponentName hostingName) {
        try {
            synchronized (ActivityManagerService.this) {
                startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
                        new HostingRecord(hostingType, hostingName),
                        false /* allowWhileBooting */, false /* isolated */,
                        true /* keepIfLarge */);
            }
        } finally {
            ......
        }
    }
    
    @GuardedBy("this")
    final ProcessRecord startProcessLocked(String processName,
            ApplicationInfo info, boolean knownToBeDead, int intentFlags,
            HostingRecord hostingRecord, boolean allowWhileBooting,
            boolean isolated, boolean keepIfLarge) {
        return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
                hostingRecord, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
                null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
                null /* crashHandler */);
    }
    

    很清晰,AMS的startProcess()调用了startProcessLocked(),而startProcessLocked()又调用了ProcessList的startProcessLocked()。

    //ProcessList.java:
    @GuardedBy("mService")
    final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
            boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord,
            boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
            String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
        ProcessRecord app;
        if (!isolated) {
            app = getProcessRecordLocked(processName, info.uid, keepIfLarge);
            ......
        } else {
            ......
        }
        ......
        final boolean success = startProcessLocked(app, hostingRecord, abiOverride);
        return success ? app : null;
    }
    
    @GuardedBy("mService")
    final boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord,
            String abiOverride) {
        return startProcessLocked(app, hostingRecord,
                false /* disableHiddenApiChecks */, false /* mountExtStorageFull */, abiOverride);
    }
    
    @GuardedBy("mService")
    boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord,
            boolean disableHiddenApiChecks, boolean mountExtStorageFull,
            String abiOverride) {
        ......
        try {
            ......
            if ("1".equals(SystemProperties.get("debug.checkjni"))) {
                runtimeFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
            }
            ......
            final String seInfo = app.info.seInfo
                    + (TextUtils.isEmpty(app.info.seInfoUser) ? "" : app.info.seInfoUser);
            // Start the process.  It will either succeed and return a result containing
            // the PID of the new process, or else throw a RuntimeException.
            final String entryPoint = "android.app.ActivityThread";
            return startProcessLocked(hostingRecord, entryPoint, app, uid, gids,
                    runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith,
                    startTime);
        } catch (RuntimeException e) {
            ......
        }
    }
    
    @GuardedBy("mService")
    boolean startProcessLocked(HostingRecord hostingRecord,
            String entryPoint,
            ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
            String seInfo, String requiredAbi, String instructionSet, String invokeWith,
            long startTime) {
        app.pendingStart = true;
        app.killedByAm = false;
        app.removed = false;
        app.killed = false;
        ......
        if (mService.mConstants.FLAG_PROCESS_START_ASYNC) {
            mService.mProcStartHandler.post(() -> {
                try {
                    final Process.ProcessStartResult startResult = startProcess(app.hostingRecord,
                            entryPoint, app, app.startUid, gids, runtimeFlags, mountExternal,
                            app.seInfo, requiredAbi, instructionSet, invokeWith, app.startTime);
                    synchronized (mService) {
                        handleProcessStartedLocked(app, startResult, startSeq);
                    }
                } catch (RuntimeException e) {
                    ......
                }
            });
            return true;
        } else {
            try {
                final Process.ProcessStartResult startResult = startProcess(hostingRecord,
                        entryPoint, app,
                        uid, gids, runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet,
                        invokeWith, startTime);
                handleProcessStartedLocked(app, startResult.pid, startResult.usingWrapper,
                        startSeq, false);
            } catch (RuntimeException e) {
                ......
            }
            return app.pid > 0;
        }
    }
    

    从上面可以看到,经过了多次同名方法 startProcessLocked() 调用,在调用过程创建了ProcessRecord对象并处理保存了进程所需的各种信息。
    最终调用的是startProcess()。

    //ProcessList.java:
    private Process.ProcessStartResult startProcess(HostingRecord hostingRecord, String entryPoint,
            ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
            String seInfo, String requiredAbi, String instructionSet, String invokeWith,
            long startTime) {
        try {
            checkSlow(startTime, "startProcess: asking zygote to start proc");
            final Process.ProcessStartResult startResult;
            if (hostingRecord.usesWebviewZygote()) {
                startResult = startWebView(entryPoint,
                        ......
            } else if (hostingRecord.usesAppZygote()) {
                final AppZygote appZygote = createAppZygoteForProcessIfNeeded(app);
    
                startResult = appZygote.getProcess().start(entryPoint,
                        ......
            } else {
                startResult = Process.start(entryPoint,
                        app.processName, uid, uid, gids, runtimeFlags, mountExternal,
                        app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                        app.info.dataDir, invokeWith, app.info.packageName,
                        new String[] {PROC_START_SEQ_IDENT + app.startSeq});
            }
            checkSlow(startTime, "startProcess: returned from zygote!");
            return startResult;
        } finally {
            ......
        }
    }
    

    这里的hostingRecord是在startProcess()调用时传入的参数new HostingRecord(hostingType, hostingName),跟踪可以看到其mHostingZygote=REGULAR_ZYGOTE。所以走的Process.start()。
     

    Zygote创建应用进程

    //Process.java:
    public static final ZygoteProcess ZYGOTE_PROCESS = new ZygoteProcess();
    
    public static ProcessStartResult start(@NonNull final String processClass,
                                               @Nullable final String niceName,
                                               int uid, int gid, @Nullable int[] gids,
                                               int runtimeFlags,
                                               int mountExternal,
                                               int targetSdkVersion,
                                               @Nullable String seInfo,
                                               @NonNull String abi,
                                               @Nullable String instructionSet,
                                               @Nullable String appDataDir,
                                               @Nullable String invokeWith,
                                               @Nullable String packageName,
                                               @Nullable String[] zygoteArgs) {
            return ZYGOTE_PROCESS.start(processClass, niceName, uid, gid, gids,
                        runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                        abi, instructionSet, appDataDir, invokeWith, packageName,
                        /*useUsapPool=*/ true, zygoteArgs);
        }
    

    ZYGOTE_PROCESS是新建的ZygoteProcess对象,在不带参数构造中定义了4中socket的地址。这里直接看ZygoteProcess.start()。

    //ZygoteProcess.java:
    public final Process.ProcessStartResult start(@NonNull final String processClass,
                                                  ......) {
        ......
        try {
            return startViaZygote(processClass, niceName, uid, gid, gids,
                    runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                    abi, instructionSet, appDataDir, invokeWith, /*startChildZygote=*/ false,
                    packageName, useUsapPool, zygoteArgs);
        } catch (ZygoteStartFailedEx ex) {
        }
    }
    
    private Process.ProcessStartResult startViaZygote(@NonNull final String processClass,
                                                      ......)
                                                      throws ZygoteStartFailedEx {
        ArrayList<String> argsForZygote = new ArrayList<>();
    
        // --runtime-args, --setuid=, --setgid=,
        // and --setgroups= must go first
        argsForZygote.add("--runtime-args");
        argsForZygote.add("--setuid=" + uid);
        argsForZygote.add("--setgid=" + gid);
        argsForZygote.add("--runtime-flags=" + runtimeFlags);
        if (mountExternal == Zygote.MOUNT_EXTERNAL_DEFAULT) {
            argsForZygote.add("--mount-external-default");
        } 
        ......
        synchronized(mLock) {
            // The USAP pool can not be used if the application will not use the systems graphics
            // driver.  If that driver is requested use the Zygote application start path.
            return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),
                                              useUsapPool,
                                              argsForZygote);
        }
    }
    

    ZygoteProcess.start()调用了startViaZygote,argsForZygote保存了启动的应用进程的完整参数。最后调用zygoteSendArgsAndGetResult()发送参数 通过socket进行通信,完成应用进程的fork,并获取结果Process.ProcessStartResult。
    这里主要看下 openZygoteSocketIfNeeded(),这个是打开Zygote socket的过程。

    //ZygoteProcess.java:
    @GuardedBy("mLock")
    private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
        try {
            attemptConnectionToPrimaryZygote();
    
            if (primaryZygoteState.matches(abi)) {
                return primaryZygoteState;
            }
            if (mZygoteSecondarySocketAddress != null) {
                // The primary zygote didn't match. Try the secondary.
                attemptConnectionToSecondaryZygote();
    
                if (secondaryZygoteState.matches(abi)) {
                    return secondaryZygoteState;
                }
            }
        } catch (IOException ioe) {
        }
    }
    
    @GuardedBy("mLock")
    private void attemptConnectionToPrimaryZygote() throws IOException {
        if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
            primaryZygoteState =
                    ZygoteState.connect(mZygoteSocketAddress, mUsapPoolSocketAddress);
    
            maybeSetApiBlacklistExemptions(primaryZygoteState, false);
            maybeSetHiddenApiAccessLogSampleRate(primaryZygoteState);
            maybeSetHiddenApiAccessStatslogSampleRate(primaryZygoteState);
        }
    }
    
    private static class ZygoteState implements AutoCloseable {
       static ZygoteState connect(@NonNull LocalSocketAddress zygoteSocketAddress,
                @Nullable LocalSocketAddress usapSocketAddress)
                throws IOException {
            ......
            final LocalSocket zygoteSessionSocket = new LocalSocket();
            .......
            try {
                zygoteSessionSocket.connect(zygoteSocketAddress);
                zygoteInputStream = new DataInputStream(zygoteSessionSocket.getInputStream());
                zygoteOutputWriter =
                        new BufferedWriter(
                                new OutputStreamWriter(zygoteSessionSocket.getOutputStream()),
                                Zygote.SOCKET_BUFFER_SIZE);
            } catch (IOException ex) {
                ......
            }
    
            return new ZygoteState(zygoteSocketAddress, usapSocketAddress,
                                   zygoteSessionSocket, zygoteInputStream, zygoteOutputWriter,
                                   getAbiList(zygoteOutputWriter, zygoteInputStream));
        }
    }
    

    openZygoteSocketIfNeeded()返回一个 ZygoteState,这个是ZygoteProcess类的内部类,是保存与zygote进程进行通信时的状态信息。
    attemptConnectionToPrimaryZygote()和attemptConnectionToSecondaryZygote()类似。通过connect()打开socket并通过ZygoteState保存状态信息。

    关于进入connect()后通过socket与zygote进程通信fork出应用进程的过程 个人也需进一步查看学习 在这里不说了。
     

    应用进程主线程-执行ActivityThread的main()

    当应用进程fork出来后,最终会执行到ActivityThread的main()方法。这个类在 AMS之AMS的启动 中说的比较多,那时主要是系统进程(system server)。关于应用进程相关的略过,这里主要是应用进程。

    //ActivityThread.java:
    public static void main(String[] args) {
        // Install selective syscall interception
        AndroidOs.install();
    
        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);
    
        Environment.initForCurrentUser();
    
        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);
    
        Process.setArgV0("<pre-initialized>");
    
        Looper.prepareMainLooper();
    
        ......
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);
    
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        ......
        Looper.loop();
    
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }
    

    这里很多熟悉的地方:
    主线程默认创建的Looper,且不可退出。在 Android消息机制(Handler)详述 详细说过。
    创建了ActivityThread对象,执行了attach(),attach()中这里第一个参数是false,即非系统进程。 AMS之AMS的启动 则是true,是系统进程。
    下面直接看下ActivityThread.attach()。
    注:此时activity还未创建,activity的attach()还在后面。

    @UnsupportedAppUsage
    //ActivityThread.java:
    private void attach(boolean system, long startSeq) {
        sCurrentActivityThread = this;
        mSystemThread = system;
        if (!system) {
            android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
                                                    UserHandle.myUserId());
            RuntimeInit.setApplicationObject(mAppThread.asBinder());
            final IActivityManager mgr = ActivityManager.getService();
            try {
                mgr.attachApplication(mAppThread, startSeq);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
            // Watch for getting close to heap limit.
            BinderInternal.addGcWatcher(new Runnable() {
                @Override public void run() {
                    if (!mSomeActivitiesChanged) {
                        return;
                    }
                    Runtime runtime = Runtime.getRuntime();
                    long dalvikMax = runtime.maxMemory();
                    long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
                    if (dalvikUsed > ((3*dalvikMax)/4)) {
                        if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
                                + " total=" + (runtime.totalMemory()/1024)
                                + " used=" + (dalvikUsed/1024));
                        mSomeActivitiesChanged = false;
                        try {
                            ActivityTaskManager.getService().releaseSomeActivities(mAppThread);
                        } catch (RemoteException e) {
                            throw e.rethrowFromSystemServer();
                        }
                    }
                }
            });
        } else {
            ......
        }
        ......
    }
    

    主要来看下mgr.attachApplication()。很明显这个也是binder机制进行跨进程的,调用的是AMS的attachApplication()。
     

    进入系统进程,将应用进程绑定到ATMS中

    //ActivityManagerService.java:
    @Override
    public final void attachApplication(IApplicationThread thread, long startSeq) {
        if (thread == null) {
            throw new SecurityException("Invalid application interface");
        }
        synchronized (this) {
            int callingPid = Binder.getCallingPid();
            final int callingUid = Binder.getCallingUid();
            final long origId = Binder.clearCallingIdentity();
            attachApplicationLocked(thread, callingPid, callingUid, startSeq);
            Binder.restoreCallingIdentity(origId);
        }
    }
    
    @GuardedBy("this")
    private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
            int pid, int callingUid, long startSeq) {
    
        // Find the application record that is being attached...  either via
        // the pid if we are running in multiple processes, or just pull the
        // next app record if we are emulating process with anonymous threads.
        ProcessRecord app;
        long startTime = SystemClock.uptimeMillis();
        long bindApplicationTimeMillis;
        if (pid != MY_PID && pid >= 0) {
            synchronized (mPidsSelfLocked) {
                app = mPidsSelfLocked.get(pid);
            }
        ......
        final String processName = app.processName;
        ......
        final BackupRecord backupTarget = mBackupTargets.get(app.userId);
        try {
            ......
            mAtmInternal.preBindApplication(app.getWindowProcessController());
            final ActiveInstrumentation instr2 = app.getActiveInstrumentation();
            if (app.isolatedEntryPoint != null) {
                // This is an isolated process which should just call an entry point instead of
                // being bound to an application.
                thread.runIsolatedEntryPoint(app.isolatedEntryPoint, app.isolatedEntryPointArgs);
            } else if (instr2 != null) {
                thread.bindApplication(processName, appInfo, providers,
                        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);
            } else {
                thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
                        null, null, null, testMode,
                        mBinderTransactionTrackingEnabled, enableTrackAllocation,
                        isRestrictedBackupMode || !normalMode, app.isPersistent(),
                        new Configuration(app.getWindowProcessController().getConfiguration()),
                        app.compat, getCommonServicesLocked(app.isolated),
                        mCoreSettingsObserver.getCoreSettingsLocked(),
                        buildSerial, autofillOptions, contentCaptureOptions);
            }
            .......
        } catch (Exception e) {
            ......
        // See if the top visible activity is waiting to run in this process...
        if (normalMode) {
            try {
                didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
            } catch (Exception e) {
                Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
                badApp = true;
            }
        }
        ......
        return true;
    }
    

    attachApplication()->attachApplicationLocked(),主要看下thread.bindApplication()和mAtmInternal.attachApplication()。
    thread.bindApplication()实际调用的是 ApplicationThread下的 bindApplication()。ApplicationThread是ActivityThread的内部类,private class ApplicationThread extends IApplicationThread.Stub。注意当前是在AMS进程,其中的thread是传入的 是应用进程主线程。
    mAtmInternal.attachApplication()最终调用的是ATMS中的 attachApplication()。

    先来看下thread.bindApplication()

    //ActivityThread.java->ApplicationThread class:
    public final void bindApplication(String processName, ApplicationInfo appInfo,
            ......) {
        ......
        data.contentCaptureOptions = contentCaptureOptions;
        sendMessage(H.BIND_APPLICATION, data);
    }
    
    //ActivityThread.java->H class:
    class H extends Handler {
        public static final int BIND_APPLICATION        = 110;
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case BIND_APPLICATION:
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
                    AppBindData data = (AppBindData)msg.obj;
                    handleBindApplication(data);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;
            }
        }
    }
    //ActivityThread.java:
    private void handleBindApplication(AppBindData data) {
        ......
        data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
        ......
        // Continue loading instrumentation.
        if (ii != null) {
            ......
            try {
                final ClassLoader cl = instrContext.getClassLoader();
                mInstrumentation = (Instrumentation)
                    cl.loadClass(data.instrumentationName.getClassName()).newInstance();
            ......
        }
        ......
        // Allow disk access during application and provider setup. This could
        // block processing ordered broadcasts, but later processing would
        // probably end up doing the same disk access.
        Application app;
    
        try {
            app = data.info.makeApplication(data.restrictedBackupMode, null);
            ......
            try {
                mInstrumentation.callApplicationOnCreate(app);
            } catch (Exception e) {
                ......
            }
        }
        ......
    }
    
    public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai,
            CompatibilityInfo compatInfo) {
        return getPackageInfo(ai, compatInfo, null, false, true, false);
    }
    
    //Application.java:
    /**
    * Called when the application is starting, before any activity, service,
    * or receiver objects (excluding content providers) have been created.
    */
    @CallSuper
    public void onCreate() {
    }
    

    这时ApplicationThread和ActivityThread在同一进程中,所以bindApplication()通过handler通信,发送message(BIND_APPLICATION),直接看到处理部分handleBindApplication()。
    通过 cl.loadClass(data.instrumentationName.getClassName()).newInstance() 反射创建了Instrumentation对象,这个在 AMS之AMS的启动 也说过。
    通过 getPackageInfoNoCheck() 创建LoadedApk对象并保存在data.info。代码流程:getPackageInfoNoCheck()->getPackageInfo()->new LoadedApk(),都在ActivityThread中。
    通过data.info.makeApplication(data.restrictedBackupMode, null)创建了Application。关键代码看下面。
    最后通过mInstrumentation.callApplicationOnCreate(app)调用了app.onCreate();,Application创建完成。
    这些操作是thread下的,前面说过是传入的 应用进程主线程。所以创建Application是在应用进程中的。

    //LoadedApk.java:   
    @UnsupportedAppUsage
    public Application makeApplication(boolean forceDefaultAppClass,
            Instrumentation instrumentation) {
        Application app = null;
        String appClass = mApplicationInfo.className;
        try {            
            java.lang.ClassLoader cl = getClassLoader();
            ......
            ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
            app = mActivityThread.mInstrumentation.newApplication(
                    cl, appClass, appContext);
            appContext.setOuterContext(app);
        } catch (Exception e) {
            
        }
        mActivityThread.mAllApplications.add(app);
        mApplication = app;  
        return app;
    }
    
    //Instrumentation.java:
    public Application newApplication(ClassLoader cl, String className, Context context)
            throws InstantiationException, IllegalAccessException, 
            ClassNotFoundException {
        Application app = getFactory(context.getPackageName())
                .instantiateApplication(cl, className);
        app.attach(context);
        return app;
    }
    
    private AppComponentFactory getFactory(String pkg) {
        ......
        return apk.getAppFactory();
    }
    
    //AppComponentFactory.java:
    public @NonNull Application instantiateApplication(@NonNull ClassLoader cl,
            @NonNull String className)
            throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        return (Application) cl.loadClass(className).newInstance();
    }
    
    //Application.java:
    /* package */ final void attach(Context context) {
        attachBaseContext(context);
        mLoadedApk = ContextImpl.getImpl(context).mPackageInfo;
    }
    //
    

    这就是makeApplication()方法创建Application的过程。注意 makeApplication()传入的instrumentation为null,Application的实例化也是通过反射。

    接着看第二点mAtmInternal.attachApplication()

    //ActivityTaskManagerService.java:
    @HotPath(caller = HotPath.PROCESS_CHANGE)
    @Override
    public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
        synchronized (mGlobalLockWithoutBoost) {
            return mRootActivityContainer.attachApplication(wpc);
        }
    }
    //RootActivityContainer.java:
    boolean attachApplication(WindowProcessController app) throws RemoteException {
        final String processName = app.mName;
        boolean didSomething = false;
        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
            final ActivityDisplay display = mActivityDisplays.get(displayNdx);
            final ActivityStack stack = display.getFocusedStack();
            if (stack != null) {
                stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
                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.mUid == activity.info.applicationInfo.uid
                            && processName.equals(activity.processName)) {
                        try {
                            if (mStackSupervisor.realStartActivityLocked(activity, app,
                                    top == activity /* andResume */, true /* checkConfig */)) {
                                didSomething = true;
                            }
                        } catch (RemoteException e) {
                            ......
                        }
                    }
                }
            }
        }
        ......
        return didSomething;
    }
    
    //ActivityStackSupervisor.java:
    boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
            boolean andResume, boolean checkConfig) throws RemoteException {
        ......
        try {
            r.startFreezingScreenLocked(proc, 0);
            // schedule launch ticks to collect information about slow apps.
            r.startLaunchTickingLocked();
            r.setProcess(proc);
            ......
            try {
                // Create activity launch transaction.
                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), 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.icicle, r.persistentState, results, newIntents,
                        dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
                                r.assistToken));
    
                // 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);
                ......
    
            } catch (RemoteException e) {
                
            }
        } finally {
        }
        ......
        return true;
    }
    

    attachApplication()关键代码 一直调用到realStartActivityLocked()。这里有几点注意。

    • 这里完善了ActivityRecord,设置了进程等信息。总体上可以理解,应为ActivityRecord、ProcessRecord等由AMS/ATMS管理,这里将application绑定到了ATMS。
    • 创建了ClientTransaction对象
    • 设置了ClientTransaction的callback,为一个创建的LaunchActivityItem对象
    • 设置生命周期,为创建的lifecycleItem对象
    • 通过mService.getLifecycleManager().scheduleTransaction(clientTransaction)发送请求。这里的mService为ATMS,这里的mService.getLifecycleManager()即ClientLifecycleManager。
    • 创建Application后,通过attachApplication()绑定到ATMS。当前还是在系统进程中。

    创建了ClientTransaction对象和设置callback的相关代码,可以了解下。

    //ClientTransaction.java
    public void addCallback(ClientTransactionItem activityCallback) {
        if (mActivityCallbacks == null) {
            mActivityCallbacks = new ArrayList<>();
        }
        mActivityCallbacks.add(activityCallback);
    }
    
    public static ClientTransaction obtain(IApplicationThread client, IBinder activityToken) {
        ClientTransaction instance = ObjectPool.obtain(ClientTransaction.class);
        if (instance == null) {
            instance = new ClientTransaction();
        }
        instance.mClient = client;
        instance.mActivityToken = activityToken;
    
        return instance;
    }
    //WindowProcessController.java:
    IApplicationThread getThread() {
        return mThread;
    }
    

    clientTransaction相关有大致了解后,直接看最后发送请求代码。

    //ClientLifecycleManager.java:
    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.java
    public void schedule() throws RemoteException {
        mClient.scheduleTransaction(this);
    }
    

    mClient是啥呢?在创建ClientTransaction对象时赋值的。mClient在obtain()时传入的,即proc.getThread(),final ClientTransaction clientTransaction = ClientTransaction.obtain(proc.getThread(), r.appToken)
    ApplicationThread是ActivityThread的内部类,继承IApplicationThread.Stub,即是一个Binder。private class ApplicationThread extends IApplicationThread.Stub
    ApplicationThread是作为Activitythread和AMS/ATMS通信的桥梁。它与ActivityThread之间通过handler通信,AMS获取ApplicationThread的binder进行通信。
    这里开始,实际就是从系统进程回到了应用进程。
    这里的过程是应用进程通过binder(IPC)执行mgr.attachApplication()进入系统进程,ATMS通过回调ApplicationThread.scheduleTransaction(),然后通过handler回到应用进程的主线程。

    ATMS回调ApplicationThread的方法,该方法在Binder线程池中的线程执行,所以需要使用Handler来切换线程到ActivityThread所在线程。

    所以这里实际调用的就是ApplicationThread的 scheduleTransaction 方法。下面来看下。

    //ActivityThread.java->ApplicationThread class:
    @Override
    public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        ActivityThread.this.scheduleTransaction(transaction);
    }
    
    //ClientTransactionHandler.java:
    /** Prepare and schedule transaction for execution. */
    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }
    
    //ActivityThread.java:
    //public final class ActivityThread extends ClientTransactionHandler
    private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
    //TransactionExecutor.java:
    /** Initialize an instance with transaction handler, that will execute all requested actions. */
    public TransactionExecutor(ClientTransactionHandler clientTransactionHandler) {
        mTransactionHandler = clientTransactionHandler;
    }
    
    
    //ActivityThread.java->H class:
    class H extends Handler {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EXECUTE_TRANSACTION:
                    final ClientTransaction transaction = (ClientTransaction) msg.obj;
                    mTransactionExecutor.execute(transaction);
                    if (isSystem()) {
                        // Client transactions inside system process are recycled on the client side
                        // instead of ClientLifecycleManager to avoid being cleared before this
                        // message is handled.
                        transaction.recycle();
                    }
                    // TODO(lifecycler): Recycle locally scheduled transactions.
                    break;
            }
        }
    }
    

    可以看到scheduleTransaction() 最终通过hanlder进行处理的,执行到TransactionExecutor的execute()。
    注意上面关于TransactionExecutor的创建,this是ActivityThread 作为参数闯入到构造函数中,ActivityThread是继承了ClientTransactionHandler的。mTransactionHandler即ActivityThread,这是应用进程的主线程,后面出现要知道。

    //TransactionExecutor.java:
    public void execute(ClientTransaction transaction) {
        ......
        executeCallbacks(transaction);
    
        executeLifecycleState(transaction);
        mPendingActions.clear();
    }
    
    /** Cycle through all states requested by callbacks and execute them at proper times. */
    @VisibleForTesting
    public void executeCallbacks(ClientTransaction transaction) {
        final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
        ......
        final int size = callbacks.size();
        for (int i = 0; i < size; ++i) {
            final ClientTransactionItem item = callbacks.get(i);
            ......
            item.execute(mTransactionHandler, token, mPendingActions);
            item.postExecute(mTransactionHandler, token, mPendingActions);
            ......
        }
    }
    

    在上面realStartActivityLocked()中,设置的callback是LaunchActivityItem对象。这里execute()最终执行到LaunchActivityItem的execute()。 继续看

    //LaunchActivityItem.java:
    @Override
    public void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
        ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
                mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
                mPendingResults, mPendingNewIntents, mIsForward,
                mProfilerInfo, client, mAssistToken);
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }
    

    上面有说过的,这里的client就是ActivityThread。所以走到了ActivityThread的handleLaunchActivity()。
     

    回到应用进程,创建activity并执行attach()和onCreate()

    这里的client就是ActivityThread,上面也说过,其实是应用进程的主线程。
    这里主要是创建出应用第一个Activity,并执行了attach()和onCreate()。

    //ActivityThread.java:
    public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
        ......
        final Activity a = performLaunchActivity(r, customIntent);
        ......
        return a;
    }
        
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ActivityInfo aInfo = r.activityInfo;
        ......
        ComponentName component = r.intent.getComponent();
        ......
        ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            ......
        }
        ......
        try {
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
            ......
            if (activity != null) {
                ......
                appContext.setOuterContext(activity);
                activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback,
                        r.assistToken);
                ......
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                ......
                r.activity = activity;
            }
            r.setState(ON_CREATE);
        }
        .......
        return activity;
    }
    

    这里是app启动中activity创建起来的最后一个阶段了。上面主要看3点

    • mInstrumentation.newActivity()创建了一个activity
    • activity.attach(),这个就是Activity中attach()的地方,将Context、ActivityThread、Instrumentation、Application、Window等等重要信息关联到了activity中。这里代码不列出了。
    • mInstrumentation.callActivityOnCreate()。执行了Activity的onCreate()方法。
      下面来看下activity的创建和如何执行到onCreate()的。

    创建activity

    //Instrumentation.java:
    public Activity newActivity(ClassLoader cl, String className,
            Intent intent)
            throws InstantiationException, IllegalAccessException,
            ClassNotFoundException {
        String pkg = intent != null && intent.getComponent() != null
                ? intent.getComponent().getPackageName() : null;
        return getFactory(pkg).instantiateActivity(cl, className, intent);
    }
    
    private AppComponentFactory getFactory(String pkg) {
        ......
    }
    
    //AppComponentFactory.java:
    public @NonNull Activity instantiateActivity(@NonNull ClassLoader cl, @NonNull String className,
            @Nullable Intent intent)
            throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        return (Activity) cl.loadClass(className).newInstance();
    }
    

    getFactory()获取的是AppComponentFactory对象。通过反射生成了Activity。

    执行Activity.onCreate()

    // Instrumentation.java
    public void callActivityOnCreate(Activity activity, Bundle icicle) {
        prePerformCreate(activity);
        activity.performCreate(icicle);
        postPerformCreate(activity);
    }
    
    // Activity.java
    final void performCreate(Bundle icicle) {
        performCreate(icicle, null);
    }
    
    @UnsupportedAppUsage
    final void performCreate(Bundle icicle, PersistableBundle persistentState) {
        ......
        if (persistentState != null) {
            onCreate(icicle, persistentState);
        } else {
            onCreate(icicle);
        }
        ......
    }
    

     

    展开全文
  • 此前在Android系统启动流程、应用进程以及深入四大组件这三个系列文章中,都提及到了AMS,但都没有系统的来讲解它,本文就以AMS为主来进行讲解,其中会有一些知识点与这些系列文章有所重合,这里会尽量做到详尽讲解...

    本文首发于微信公众号「刘望舒」

    关联系列
    Android系统启动流程系列
    Android应用进程系列
    Android深入四大组件系列

    前言

    此前在Android系统启动流程、应用进程以及深入四大组件这三个系列文章中,都提及到了AMS,但都没有系统的来讲解它,本文就以AMS为主来进行讲解,其中会有一些知识点与这些系列文章有所重合,这里会尽量做到详尽讲解。阅读此文章前,最好阅读相关文章中列出的系列文章,否则我不敢保证这篇文章你能看的懂。

    1.概述

    AMS是系统的引导服务,应用进程的启动、切换和调度、四大组件的启动和管理都需要AMS的支持。从这里可以看出AMS的功能会十分的繁多,当然它并不是一个类承担这个重责,它有一些关联类,这在文章后面会讲到。AMS的涉及的知识点非常多,这篇文章主要会讲解AMS的以下几个知识点:

    • AMS的启动流程。
    • AMS与进程启动。
    • AMS家族。

    2.AMS的启动流程

    AMS的启动是在SyetemServer进程中启动的,在Android系统启动流程(三)解析SyetemServer进程启动过程这篇文章中提及过,这里从SyetemServer的main方法开始讲起:
    frameworks/base/services/java/com/android/server/SystemServer.java

    public static void main(String[] args) {
           new SystemServer().run();
       }
    

    main方法中只调用了SystemServer的run方法,如下所示。
    frameworks/base/services/java/com/android/server/SystemServer.java

    private void run() {
           ...
               System.loadLibrary("android_servers");//1
           ...
               mSystemServiceManager = new SystemServiceManager(mSystemContext);//2
               LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
           ...    
            try {
               Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices");
               startBootstrapServices();//3
               startCoreServices();//4
               startOtherServices();//5
           } catch (Throwable ex) {
               Slog.e("System", "******************************************");
               Slog.e("System", "************ Failure starting system services", ex);
               throw ex;
           } finally {
               Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
           }
           ...
       }
    

    在注释1处加载了动态库libandroid_servers.so。接下来在注释2处创建SystemServiceManager,它会对系统的服务进行创建、启动和生命周期管理。在注释3中的startBootstrapServices方法中用SystemServiceManager启动了ActivityManagerService、PowerManagerService、PackageManagerService等服务。在注释4处的startCoreServices方法中则启动了BatteryService、UsageStatsService和WebViewUpdateService。注释5处的startOtherServices方法中启动了CameraService、AlarmManagerService、VrManagerService等服务。这些服务的父类均为SystemService。从注释3、4、5的方法可以看出,官方把系统服务分为了三种类型,分别是引导服务、核心服务和其他服务,其中其他服务是一些非紧要和一些不需要立即启动的服务。系统服务总共大约有80多个,我们主要来查看引导服务AMS是如何启动的,注释3处的startBootstrapServices方法如下所示。

    frameworks/base/services/java/com/android/server/SystemServer.java

       private void startBootstrapServices() {
            Installer installer = mSystemServiceManager.startService(Installer.class);
            // Activity manager runs the show.
            mActivityManagerService = mSystemServiceManager.startService(
                    ActivityManagerService.Lifecycle.class).getService();//1
            mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
            mActivityManagerService.setInstaller(installer);
          ...
        }
    

    在注释1处调用了SystemServiceManager的startService方法,方法的参数是ActivityManagerService.Lifecycle.class:
    frameworks/base/services/core/java/com/android/server/SystemServiceManager.java

      @SuppressWarnings("unchecked")
        public <T extends SystemService> T startService(Class<T> serviceClass) {
            try {
               ...
                final T service;
                try {
                    Constructor<T> constructor = serviceClass.getConstructor(Context.class);//1
                    service = constructor.newInstance(mContext);//2
                } catch (InstantiationException ex) {
                  ...
                }
                // Register it.
                mServices.add(service);//3
                // Start it.
                try {
                    service.onStart();//4
                } catch (RuntimeException ex) {
                    throw new RuntimeException("Failed to start service " + name
                            + ": onStart threw an exception", ex);
                }
                return service;
            } finally {
                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
            }
        }
    

    startService方法传入的参数是Lifecycle.class,Lifecycle继承自SystemService。首先,通过反射来创建Lifecycle实例,注释1处得到传进来的Lifecycle的构造器constructor,在注释2处调用constructor的newInstance方法来创建Lifecycle类型的service对象。接着在注释3处将刚创建的service添加到ArrayList类型的mServices对象中来完成注册。最后在注释4处调用service的onStart方法来启动service,并返回该service。Lifecycle是AMS的内部类,代码如下所示。
    frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

       public static final class Lifecycle extends SystemService {
            private final ActivityManagerService mService;
            public Lifecycle(Context context) {
                super(context);
                mService = new ActivityManagerService(context);//1
            }
            @Override
            public void onStart() {
                mService.start();//2
            }
            public ActivityManagerService getService() {
                return mService;//3
            }
        }
    

    上面的代码结合SystemServiceManager的startService方法来分析,当通过反射来创建Lifecycle实例时,会调用注释1处的方法创建AMS实例,当调用Lifecycle类型的service的onStart方法时,实际上是调用了注释2处AMS的start方法。在SystemServer的startBootstrapServices方法的注释1处,调用了如下代码:

     mActivityManagerService = mSystemServiceManager.startService(
                    ActivityManagerService.Lifecycle.class).getService();
    

    我们知道SystemServiceManager的startService方法最终会返回Lifecycle类型的对象,紧接着又调用了Lifecycle的getService方法,这个方法会返回AMS类型的mService对象,见注释3处,这样AMS实例就会被创建并且返回。

    3.AMS与进程启动

    Android系统启动流程(二)解析Zygote进程启动过程这篇文章中,我提到了Zygote的Java框架层中,会创建一个Server端的Socket,这个Socket用来等待AMS来请求Zygote来创建新的应用程序进程。要启动一个应用程序,首先要保证这个应用程序所需要的应用程序进程已经被启动。AMS在启动应用程序时会检查这个应用程序需要的应用程序进程是否存在,不存在就会请求Zygote进程将需要的应用程序进程启动。Service的启动过程中会调用ActiveServices的bringUpServiceLocked方法,如下所示。
    frameworks/base/services/core/java/com/android/server/am/ActiveServices.java

      private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
                boolean whileRestarting, boolean permissionsReviewRequired)
                throws TransactionTooLargeException {
      ...
      final String procName = r.processName;//1
      ProcessRecord app;
      if (!isolated) {
                app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);//2
                if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
                            + " app=" + app);
                if (app != null && app.thread != null) {//3
                    try {
                        app.addPackage(r.appInfo.packageName, r.appInfo.versionCode,
                        mAm.mProcessStats);
                        realStartServiceLocked(r, app, execInFg);//4
                        return null;
                    } catch (TransactionTooLargeException e) {
                  ...
                }
            } else {
                app = r.isolatedProc;
            }
     if (app == null && !permissionsReviewRequired) {//5
                if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
                        "service", r.name, false, isolated, false)) == null) {//6
                  ...
                }
                if (isolated) {
                    r.isolatedProc = app;
                }
            }
     ...     
    }
    

    在注释1处得到ServiceRecord的processName的值赋值给procName ,其中ServiceRecord用来描述Service的android:process属性。注释2处将procName和Service的uid传入到AMS的getProcessRecordLocked方法中,来查询是否存在一个与Service对应的ProcessRecord类型的对象app,ProcessRecord主要用来记录运行的应用程序进程的信息。注释5处判断Service对应的app为null则说明用来运行Service的应用程序进程不存在,则调用注释6处的AMS的startProcessLocked方法来创建对应的应用程序进程,
    具体的过程请查看Android应用程序进程启动过程(前篇)

    4.AMS家族

    ActivityManager是一个和AMS相关联的类,它主要对运行中的Activity进行管理,这些管理工作并不是由ActivityManager来处理的,而是交由AMS来处理,ActivityManager中的方法会通过ActivityManagerNative(以后简称AMN)的getDefault方法来得到ActivityManagerProxy(以后简称AMP),通过AMP就可以和AMN进行通信,而AMN是一个抽象类,它会将功能交由它的子类AMS来处理,因此,AMP就是AMS的代理类。AMS作为系统核心服务,很多API是不会暴露给ActivityManager的,因此ActivityManager并不算是AMS家族一份子。
    为了讲解AMS家族,这里拿Activity的启动过程举例,Activity的启动过程中会调用Instrumentation的execStartActivity方法,如下所示。
    frameworks/base/core/java/android/app/Instrumentation.java

    public ActivityResult execStartActivity(
                Context who, IBinder contextThread, IBinder token, Activity target,
                Intent intent, int requestCode, Bundle options) {
          ...
            try {
                intent.migrateExtraStreamToClipData();
                intent.prepareToLeaveProcess(who);
                int result = ActivityManagerNative.getDefault()
                    .startActivity(whoThread, who.getBasePackageName(), 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;
        }
    

    execStartActivity方法中会调用AMN的getDefault来获取AMS的代理类AMP。接着调用了AMP的startActivity方法,先来查看AMN的getDefault方法做了什么,如下所示。
    frameworks/base/core/java/android/app/ActivityManagerNative.java

     static public IActivityManager getDefault() {
            return gDefault.get();
        }
        private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
            protected IActivityManager create() {
                IBinder b = ServiceManager.getService("activity");//1
                if (false) {
                    Log.v("ActivityManager", "default service binder = " + b);
                }
                IActivityManager am = asInterface(b);//2
                if (false) {
                    Log.v("ActivityManager", "default service = " + am);
                }
                return am;
            }+
        };
    }
    

    getDefault方法调用了gDefault的get方法,我们接着往下看,gDefault 是一个Singleton类。注释1处得到名为”activity”的Service引用,也就是IBinder类型的AMS的引用。接着在注释2处将它封装成AMP类型对象,并将它保存到gDefault中,此后调用AMN的getDefault方法就会直接获得AMS的代理对象AMP。注释2处的asInterface方法如下所示。
    frameworks/base/core/java/android/app/ActivityManagerNative.java

    static public IActivityManager asInterface(IBinder obj) {
        if (obj == null) {
            return null;
        }
        IActivityManager in =
            (IActivityManager)obj.queryLocalInterface(descriptor);
        if (in != null) {
            return in;
        }
        return new ActivityManagerProxy(obj);
    }
    

    asInterface方法的主要作用就是将IBinder类型的AMS引用封装成AMP,AMP的构造方法如下所示。

    frameworks/base/core/java/android/app/ActivityManagerNative.java

    class ActivityManagerProxy implements IActivityManager
    {
        public ActivityManagerProxy(IBinder remote)
        {
            mRemote = remote;
        }
    ...
     }
    

    AMP的构造方法中将AMS的引用赋值给变量mRemote ,这样在AMP中就可以使用AMS了。
    其中IActivityManager是一个接口,AMN和AMP都实现了这个接口,用于实现代理模式和Binder通信。
    再回到Instrumentation的execStartActivity方法,来查看AMP的startActivity方法,AMP是AMN的内部类,代码如下所示。
    frameworks/base/core/java/android/app/ActivityManagerNative.java

    public int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
               String resolvedType, IBinder resultTo, String resultWho, int requestCode,
               int startFlags, ProfilerInfo profilerInfo, Bundle options) throws RemoteException {
         ...
           data.writeInt(requestCode);
           data.writeInt(startFlags);
         ...
           mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);//1
           reply.readException();+
           int result = reply.readInt();
           reply.recycle();
           data.recycle();
           return result;
       }
    

    首先会将传入的参数写入到Parcel类型的data中。在注释1处,通过IBinder类型对象mRemote(AMS的引用)向服务端的AMS发送一个START_ACTIVITY_TRANSACTION类型的进程间通信请求。那么服务端AMS就会从Binder线程池中读取我们客户端发来的数据,最终会调用AMN的onTransact方法,如下所示。
    frameworks/base/core/java/android/app/ActivityManagerNative.java

       @Override
       public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
               throws RemoteException {
           switch (code) {
           case START_ACTIVITY_TRANSACTION:
           {
           ...
               int result = startActivity(app, callingPackage, intent, resolvedType,
                       resultTo, resultWho, requestCode, startFlags, profilerInfo, options);
               reply.writeNoException();
               reply.writeInt(result);
               return true;
           }
       }
    

    onTransact中会调用AMS的startActivity方法,如下所示。
    frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

     @Override
     public final int startActivity(IApplicationThread caller, String callingPackage,
             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
         return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                 resultWho, requestCode, startFlags, profilerInfo, bOptions,
                 UserHandle.getCallingUserId());
     }
    

    startActivity方法会最后return startActivityAsUser方法,如下所示。
    frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

     @Override
     public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
         enforceNotIsolatedCaller("startActivity");
         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
                 userId, false, ALLOW_FULL_ONLY, "startActivity", null);
         return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
                 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
                 profilerInfo, null, null, bOptions, false, userId, null, null);
      }           
    

    startActivityAsUser方法最后会return ActivityStarter的startActivityMayWait方法,这一调用过程已经脱离了本节要讲的AMS家族,因此这里不做介绍了,具体的调用过程可以查看Android深入四大组件(一)应用程序启动过程(后篇)这篇文章。

    在Activity的启动过程中提到了AMP、AMN和AMS,它们共同组成了AMS家族的主要部分,如下图所示。

    VeigPS.png

    AMP是AMN的内部类,它们都实现了IActivityManager接口,这样它们就可以实现代理模式,具体来讲是远程代理:AMP和AMN是运行在两个进程的,AMP是Client端,AMN则是Server端,而Server端中具体的功能都是由AMN的子类AMS来实现的,因此,AMP就是AMS在Client端的代理类。AMN又实现了Binder类,这样AMP可以和AMS就可以通过Binder来进行进程间通信。

    ActivityManager通过AMN的getDefault方法得到AMP,通过AMP就可以和AMN进行通信,也就是间接的与AMS进行通信。除了ActivityManager,其他想要与AMS进行通信的类都需要通过AMP,如下图所示。

    Vei658.png

    参考资料
    [深入理解Android卷二 全文-第六章]深入理解ActivityManagerService
    Framework源码分析(一):ActivityManagerService
    ActivityManager与Proxy模式的运用


    这里不仅分享大前端、Android、Java等技术,还有程序员成长类文章。
    展开全文
  • 安卓系统框架学习_AMS启动流程 本文参考https://blog.csdn.net/renshuguo123723/article/details/85332146 AMS的启动流程 1:SystemServer#main -> 2:SystemServer#run -> 3:SystemServiceManager#...

    【安卓开机启动】 AMS启动

    本文参考https://blog.csdn.net/renshuguo123723/article/details/85332146

    AMS,即ActivityManagerService,是安卓java framework的一个服务,运行在system_server进程。此服务十分重要,因为它管理着安卓的四大组件,是安卓APP开发者最常接触到的一个服务。

    AMS的启动流程
    1:SystemServer#main -> 2:SystemServer#run -> 3:SystemServiceManager#startBootstrapServices
    1:首先SystemServer进程运行main函数, main函数内部只调用了一个自己的run()方法.

     public static void main(String[] args) {
            new SystemServer().run();
        }
    

    2:SystemServer的run()方法注释非常多,可以自己看一下.中文注释没有使用//了, 不然颜色比较难以看清

     private void run() {
           <--开始!-->
                // Prepare the main looper thread (this thread).
                <--准备主线程(该线程)-->
                android.os.Process.setThreadPriority(
                    android.os.Process.THREAD_PRIORITY_FOREGROUND);
                android.os.Process.setCanSelfBackground(false);
                Looper.prepareMainLooper();
                Looper.getMainLooper().setSlowLogThresholdMs(
                        SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
    
                <--初始化native服务-->
                System.loadLibrary("android_servers");
    
                <--初始化系统上下文-->
                createSystemContext();
    
                <--创建system service manager!!!-->    
                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();
     
    
           <--打开系统服务-->
                <--启动引导服务-->
                <--用SystemServiceManager启动了ActivityManagerService、PowerManagerService、 PackageManagerService等服务-->
                startBootstrapServices();
    
                <--核心服务-->
                <--启动BatteryService、UsageStatsService和WebViewUpdateService-->
                startCoreServices();
    
                <--启动其他服务-->
                <--启动了WMS,CameraService、AlarmManagerService、VrManagerService等服务-->
                startOtherServices();
    
          <--Loop forever-->
            Looper.loop();
            throw new RuntimeException("Main thread loop unexpectedly exited");
        }
    

    3:SystemServer的startBootstrapServices()方法

    SystemServer.java
    //启动AMS
     private void startBootstrapServices() {
     		...
    		<--调用SystemServiceManager的startSErvice()方法, 传入Lifecycle.class字节码文件的参数, 
    		通过反射实例化Lifecycle对象,并启动AMS(通过这个参数"ActivityManagerService.Lifecycle.class"可以看出
    		Lifecycle是AMS的一个内部类)-->
            mActivityManagerService = mSystemServiceManager.startService(
                    ActivityManagerService.Lifecycle.class).getService();
    
            mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    
            mActivityManagerService.setInstaller(installer);
     }
    
    SystemServiceManager.java
     public SystemService startService(String className) {
           	<--使用反射获取.class文件-->
            Class serviceClass = Class.forName(className);
            return this.startService(serviceClass);
        }
    SystemServiceManager.java
     public <T extends SystemService> T startService(Class<T> serviceClass) {
            String name = serviceClass.getName();
            SystemService service;
            Constructor<T> constructor = serviceClass.getConstructor(Context.class);
            
            <--通过反射,调用constructor的newInstance方法来创建Lifecycle类型的service对象-->
            service = (SystemService)constructor.newInstance(this.mContext);
            
            <--把该服务加入到系统服务集合当中, 该系统服务集合就是SystemServiceManager类的list类型的成员变量-->
        	this.mServices.add(service);
        	
        	<--调用反射类的onStart()方法开启AMS服务(实际上Lifecycle内部类虽然是静态的, 
        	但是显示的拥有一个AMS的对象, 该方法就是利用这个AMS对象调用AMS的start()方法)-->
    		service.onStart();
    		<--返回该服务-->
            return service; 
      }
    
    

    2021年7月4日补全

    19年的时候初入安卓系统开发的岗位,对整个系统的认识比较少。
    现在看来AMS的启动过程相对来说是比较简单的。
    在系统开机启动之后,system_server会执行三大服务启动

    1. startBootstrapServices() 启动引导服务,在这里实际上已经new了AMS,在new方法里,已经初始化了AMS的大部分重要的属性。AMS的Looper和各种handler也是在这里准备好的。
    private void startBootstrapServices() {
       	...
           ActivityTaskManagerService atm = mSystemServiceManager.startService(
                   ActivityTaskManagerService.Lifecycle.class).getService();
           		mActivityManagerService = ActivityManagerService.Lifecycle.startService(
                   mSystemServiceManager, atm);
           		mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
           		mActivityManagerService.setInstaller(installer);
           ...
    }
    
       public static final class Lifecycle extends SystemService {
           private final ActivityManagerService mService;
           private static ActivityTaskManagerService sAtm;
    
           public Lifecycle(Context var1) {
               super(var1);
               this.mService = new ActivityManagerService(var1, sAtm);
           }
    
           public static ActivityManagerService startService(SystemServiceManager var0, ActivityTaskManagerService var1) {
               sAtm = var1;
               return ((ActivityManagerService.Lifecycle)var0.startService(ActivityManagerService.Lifecycle.class)).getService();
           }
    
    1. 在创建完AMS之后,system_server的run方法会执行到startOtherServices(),在启动“其他服务”完毕之后,会调入到AMS的systemReady()方法,在这里会启动launcher。
      可以说,在这个方法执行完毕之后,系统就已经启动完成了。如果我们先要在系统启动的过程中在java framework中加入自己的代码,可以在systemReady()这个方法中,完成。(比如注册自己的广播接受器)
    public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
                if (bootingSystemUser) {
                    mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
                }
     }           
    

    最后在强调一下AMS的功能吧,它主要是用来管理四大组件的。

    展开全文
  • android系统服务,Activity管理的服务端,用于管理activity的各种行为,控制activity的生命周期,派发消息事件,低内存管理等等。实现了IBinder接口,可以用于进程间通信 Activity.java ActivityRecord.java ...
  • Android AMS源码阅读分析(一)

    千次阅读 2019-01-22 20:41:00
    最近学习了柯元旦所著《Android内核剖析》之AMS原理篇章,结合自己的理解以及对源码的分析,记录一下学习心得,AMS代码非常多,而且和Application以及Activity之间的交互也相对繁杂,这里学习大致的主干流程,之后有...
  • android AMS原理解析

    2021-01-11 18:02:23
    startactivity app启动过程 启动下半场,AMS返回后 部分结构继承关系
  • android AMS

    万次阅读 多人点赞 2018-03-18 14:29:31
    AMSAndroid中最核心的服务,主要负责系统中四大组件的启动、切换、调度及应用进程的管理和调度等工作,其职责与操作系统中的进程管理和调度模块相类似,因此它在Android中非常重要。 ActivityManagerService ...
  • Android AMS原理分析(1)

    千次阅读 2017-03-22 11:38:37
    应用程序需要启动Activity–>报告给AMS,决定是否可以启动–>如果可以,通知应用程序运行指定Activity。AMS必须知道各个应用程序运行的Activity。 内存管理。 Activity退出时不会立即被杀死,只有在内存紧张时才会...
  • 摘要:上一节我们讲完了SystemServer的启动过程,这一节接着上一节的步骤,来讲解ActivityManagerService的启动过程。 ActivityManagerService简称AMS,具有管理Activity行为、控制activity的生命周期、派发消息...
  • Android AMS的理解

    2021-07-08 10:36:41
    AMS(ActivityManagerService)是Android中最核心的服务,主要负责系统中四大组件的启动、切换、调度及应用进程的管理和调度等工作,其职责与操作系统中的进程管理和调度模块相类似。 AMS服务运行在system_server进程...
  • 深入理解Android AMS

    2020-03-16 21:22:34
    在activity的启动过程中会调用Instrumentation的execStartActivity方法: 涉及代码: Instrumentation.java core\java\android\app\Instrumentation.java 这里调用到了ActivityManager的getService方法: ...
  • 1. Android Framework - 学习启动篇 2. Android Framework - 开机启动 SystemServer 进程 相关源码文件: /frameworks/base/services/java/com/android/server/SystemServer.java /frameworks/base/services/core/...
  • 源码分析Android AMS WMS PMS

    千次阅读 2018-03-17 16:39:26
    今天谈谈Android三大系统服务... Android手机一开机的流程,开机启动,在Java层入口是SystemServer,代码如下 android.os.Process.setThreadPriority(); Looper.prepareMainLooper(); // 创建systemserver上进程...
  • Android7.0点击Launcher后的应用启动流程,主要介绍的是AMS部分。
  • APP启动流程详解

    2018-02-03 18:24:49
    详细的解说了APP的启动过程及其核心代码,为学习Android framework框架提供了很好的学习资料
  • AMS启动流程

    2019-01-27 04:32:49
    在SystemServer中简单分析了AMS流程,这篇就详细地讲解AMS启动流程 注意一点:AMS所在的进程是属于SystemServer中的 时序图 AMS流程 创建AMS对象 调用ams.setSystemProcess 调用ams.installSystemProviders 调用...
  • Android AMS 与 APP 进程通信

    千次阅读 2019-05-10 10:54:31
    概述 在 Android 中,APK 运行在 App 进程,而 AMS 运行在 system_server 进程,AMS 承担着对 Activity 的生命周期的...那么理解 AMS 进程和 App 进程之间的通信就对 Activity 的启动流程的理解有很好的铺垫作用。...
  • Android AMS

    2020-09-10 15:09:14
    ActivityManagerService是Android系统中一个特别重要的系统服务,也是我们上层APP打交道最多的系统服务之一,ActivityManagerService(以下简称AMS) 主要负责四大组件的启动、切换、调度以及应用进程的管理和调度...
  • 一、Activity 启动过程可以说明AMS的作用 二、AMS与ActivityThread的交互关系 系统机制 三、hookams 启动Activity 会去调用哪些AMS 首先可以看一下Android启动流程 然后我们可以回顾以下Activity 的启动流程...
  • Android系统中,有两种操作会引发Activity的启动: 一种用户点击应用程序图标时,Launcher会为我们启动应用程序的主Activity; 而另一种当应用程序的默认Activity启动起来后,它又可以在内部通过调用startActvity...
  • 在之前学习了AMS如何与客户进程进行交互,从而实现启动应用进程并且创建application以及activity,调用activity生命周期进行界面显示的过程。那么当activity显示了之后,如何停止呢?现在就来学习一下,activity停止...
  • android AMS 详解一

    千次阅读 2015-05-15 18:14:27
    前言:之前 android SystemServer详解 分析了一下systemserver的启动过程,虽然分析下来很多繁琐,可以systemserver却是android启动的第一步,很多service都是在这个进程中启动,这些才是组成android的关键,AMS可以...
  • 首先提到AMS(ActivityManagerService)我们先来了解一下Android系统的启动流程,以及AMS是什么时候创建的。 启动到SystemServer这时才会启动一些列的系统服务,其中包括 1.引导服务,例如 ActivityManagerService...
  • Android App启动流程详解

    万次阅读 多人点赞 2019-06-26 15:26:19
    前言:在之前的文章中已经写了apk的打包流程、安装流程,今天就是梳理一下apk系列的最后的流程--app启动流程。经过今天的梳理以后咱们就可以对apk包是怎么编译生成的、apk是怎么被安装到安卓手机的、用户点击了桌面...
  • AMS
  • Android AMS 浅析

    2017-07-27 11:08:26
    AMS(ActivityManagerService)Android的核心服务之一,对于framework各个核心服务,如果不是专门去做framework开发,先了解其基本的流程机制,再慢慢深究,整个framework框架还是比较庞大的,由于之前跟踪修改phone...
  • android Activity启动流程

    2021-01-03 22:57:40
    Activity的启动过程,我们可以从Context的startActivity说起,其实现是ContextImpl的startActivity,然后内部会通过Instrumentation来尝试启动Activity,这是一个跨进程过程,它会调用ams的startActivity方法,当AMS...
  • android架构(AMS

    2020-04-01 19:23:37
    android架构(AMS)Android架构LoaderKernelNativeFrameworkApp通信方式BinderHandler系统启动AMSAMS启动AMS类图结构 Android架构 Android系统启动过程:Loader -> Kernel -> Native -> Framework -> ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 11,812
精华内容 4,724
关键字:

androidams启动流程