Activity发动流程

Android Framework之Activity启动流程

流程图太大了,这儿显现不全,能够在后面时序总图中方大检查。

发动Activty触发点为Activity中的startActivity。

Activity startActivity ->

Instrumentation –> execStartActivity

try {
    intent.migrateExtraStreamToClipData(who);
    intent.prepareToLeaveProcess(who);
    //
    int result = android.app.ActivityTaskManager.getService().startActivity(whoThread,
            who.getBasePackageName(), who.getAttributionTag(), intent,
            intent.resolveTypeIfNeeded(who.getContentResolver()), token,
            target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
    checkStartActivityResult(result, intent);
} catch (RemoteException e) {
    throw new RuntimeException("Failure from system", e);
}
/** @hide */
public static IActivityTaskManager getService() {
    //经过aidl接口获取ActivityTaskManagerService操作目标
    return IActivityTaskManagerSingleton.get();
}

经过aidl接口得到ActivityTaskManagerService的目标(简称ATMS),activity发动本来是ams办理的,在android10之后增加了ATMS,将本来AMS中的部分代码移动了此类中。

Android Framework之Activity启动流程

Instrumentation中调用了execStartActivity之后,终究调用了ATMS中的startActivityAsUser()办法。

@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
        String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
        String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
        Bundle bOptions) {
    return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
            resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
            UserHandle.getCallingUserId());
}
private int startActivityAsUser(IApplicationThread caller, String callingPackage,
        @Nullable String callingFeatureId, Intent intent, String resolvedType,
        IBinder resultTo, String resultWho, int requestCode, int startFlags,
        ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
    assertPackageMatchesCallingUid(callingPackage);
    enforceNotIsolatedCaller("startActivityAsUser");
    userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
            Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
    // TODO: Switch to user app stacks here.
    //经过ActivityStartController终究调用到了ActivityStarter中的execute办法。
    return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
            .setCaller(caller)
            .setCallingPackage(callingPackage)
            .setCallingFeatureId(callingFeatureId)
            .setResolvedType(resolvedType)
            .setResultTo(resultTo)
            .setResultWho(resultWho)
            .setRequestCode(requestCode)
            .setStartFlags(startFlags)
            .setProfilerInfo(profilerInfo)
            .setActivityOptions(bOptions)
            .setUserId(userId)
            .execute();
}

经过ActivityStartController终究调用到了ActivityStarter中的execute办法。

execute办法办法调用:startActivityInner—> deliverToCurrentTopIfNeeded

RootWindowContainer–>resumeFocusedStacksTopActivities

ActivityStack–>resumeTopActivityUncheckedLocked–>resumeTopActivityInnerLocked

在resumeTopActivityInnerLocked结尾处调用了ActivityStackSupervisor中的startSpecificActivity办法。

Android Framework之Activity启动流程

ActivityStackSupervisor—>startSpecificActivity 代码如下:

void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
    // Is this activity's application already running?
    final WindowProcessController wpc =
            mService.getProcessController(r.processName, r.info.applicationInfo.uid);
    boolean knownToBeDead = false;
    if (wpc != null && wpc.hasThread()) {
        try {
            realStartActivityLocked(r, wpc, andResume, checkConfig);
            return;
        } catch (RemoteException e) {
            Slog.w(TAG, "Exception when starting activity "
                    + r.intent.getComponent().flattenToShortString(), e);
        }
        // If a dead object exception was thrown -- fall through to
        // restart the application.
        knownToBeDead = true;
    }
    r.notifyUnknownVisibilityLaunchedForKeyguardTransition();
    final boolean isTop = andResume && r.isTopRunningActivity();
    mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
}

此处,假如有app进程,则直接调用realStartActivityLocked办法。

假如没有进程,则去发动进程,咱们进入mService.startProcessAsync() 代码,进行跟踪。

ActivityTaskManagerService–>startProcessAsync

Android Framework之Activity启动流程

办法中调用了这个办法:ActivityManagerInternal::startProcess,这个接口直接回调到了AMS中的startProcess。

ActivityManagerService–>startProcess–> startProcessLocked

ProcessList–>startProcessLocked–>startProcessLocked

Android Framework之Activity启动流程

final String entryPoint = “android.app.ActivityThread”; 这个值很关键

startProcessLocked办法持续往下。

startProcessLocked–>startProcess–>startProcess()–>createAppZygoteForProcessIfNeeded

Android Framework之Activity启动流程

Android Framework之Activity启动流程

创立AppZygote目标,保存到zygote调集中,并回来此目标。

创立appzygote目标之后,直接调用start办法。

Android Framework之Activity启动流程

此刻来到了ZygoteProcess类中的start办法。

ZygoteProcess–>start()–>startViaZygote()

Android Framework之Activity启动流程

start办法调用后会依据传入的processClass参数进行创立新的进程然后调用该进程的main办法,在start函数reture之后创立出来的进程不受影响,持续运行。

进入到startViaZygote办法之内。

Android Framework之Activity启动流程

调用zygoteSendArgsAndGetResult,留意入参,会检查是否需要树立socket链接进行通讯。

进入openZygoteSocketIfNeeded办法,终究调用connect办法。

Android Framework之Activity启动流程

/**
 * @hide for internal use only
 */
public static final int SOCKET_BUFFER_SIZE = 256;

先是创立一个LocalSocket,然后connect链接,并设置了传输buffer字节约束,SOCKET_BUFFER_SIZE=256.

socket链接之后,咱们回到zygoteSendArgsAndGetResult,进入该办法中。

Android Framework之Activity启动流程

进入到 attemptUsapSendArgsAndGetResult 办法中,写入音讯:

Android Framework之Activity启动流程

前面传入的 final String entryPoint = “android.app.ActivityThread” 值便是processClass,被socket发送了出去。

Zygote检查接纳办法,假如调用进程的main办法的。

zygote初始化的时分会敞开一个无限循环,一向读取发送过来的值。

ZygoteInit –>main()

ZygoteServer –> runSelectLoop()

Android Framework之Activity启动流程

进入到processOneCommand办法中,持续调用 handleChildProc 办法,终究调用Zygote中的 childZygoteInit 办法。

ZygoteServer –> runSelectLoop()

ZygoteConnection –> processOneCommand()–> handleChildProc()

processOneCommand的办法如下:

Android Framework之Activity启动流程

readArgumentList便是读取localSocket发送过来的值。(android.app.ActivityThread 这个processClass字符参数就被发送到了这儿)

ZygoteInit –> childZygoteInit()

/**
 * The main function called when starting a child zygote process. This is used as an alternative
 * to zygoteInit(), which skips calling into initialization routines that start the Binder
 * threadpool.
 */
static final Runnable childZygoteInit(
        int targetSdkVersion, String[] argv, ClassLoader classLoader) {
    RuntimeInit.Arguments args = new RuntimeInit.Arguments(argv);
    return RuntimeInit.findStaticMain(args.startClass, args.startArgs, classLoader);
}

RuntimeInit–>findStaticMain() 经过反射调用class的main办法。

Android Framework之Activity启动流程

传递进来的className是ActivityThread,所以此处反射的便是ActivityThread的main办法,咱们直接进入其中看下代码。

ActivityThread.main()

代码如下:

public static void main(String[] args) {
    ……………………
    Looper.prepareMainLooper();
    // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
    // It will be in the format "seq=114"
    long startSeq = 0;
    if (args != null) {
        for (int i = args.length - 1; i >= 0; --i) {
            if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
                startSeq = Long.parseLong(
                        args[i].substring(PROC_START_SEQ_IDENT.length()));
            }
        }
    }
    ActivityThread thread = new ActivityThread();
    thread.attach(false, startSeq);
    …………………
    // End of event ActivityThreadMain.
    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

ActivityThread –> main()–>attach(false)

Android Framework之Activity启动流程

留意此处的attach传入的参数是false,不是true,咱们不要看到下面的 createAppContext中创立context逻辑里面去了。

IActivityManager –> attachApplication(); 此类是aidl接口,让ActivityThread和AMS直接通讯。

ActivityManageService–> attachApplication() 这个办法很长,大约四百多行,咱们直接搜索参数thread运用的当地,找到了thread.bindApplication();

ActivityThread–>bindApplication() –>sendMessage(H.BIND_APPLICATION, data)–>handleBindApplication()

Android Framework之Activity启动流程

图片中红色箭头处是创立applicatio的流程:

LoadedApk–>makeApplication()

Instumentation–> newApplication()

Application –> attach()–>attachBaseContext()

ContextWrapper –>attachBaseContext()

此刻的Application创立好之后,并没有发现履行application的onCreate办法,所以咱们需要回到ActtivityThread中的当时代码节点持续往下看。

try {
    //创立application
    app = data.info.makeApplication(data.restrictedBackupMode, null);
    if (!data.restrictedBackupMode) {
        if (!ArrayUtils.isEmpty(data.providers)) {
             //初始化contentProvider
            installContentProviders(app, data.providers);
        }
    }
    try {
        mInstrumentation.onCreate(data.instrumentationArgs);
    }
    catch (Exception e) {
        throw new RuntimeException(
            "Exception thrown in onCreate() of "
            + data.instrumentationName + ": " + e.toString(), e);
    }
    try {
        //回调application的onCreate办法
        mInstrumentation.callApplicationOnCreate(app);
    } catch (Exception e) {
        if (!mInstrumentation.onException(app, e)) {
            throw new RuntimeException(
              "Unable to create application " + app.getClass().getName()
              + ": " + e.toString(), e);
        }
    }
} finally {
    // If the app targets < O-MR1, or doesn't change the thread policy
    // during startup, clobber the policy to maintain behavior of b/36951662
    if (data.appInfo.targetSdkVersion < Build.VERSION_CODES.O_MR1
            || StrictMode.getThreadPolicy().equals(writesAllowedPolicy)) {
        StrictMode.setThreadPolicy(savedPolicy);
    }
}

咱们进入到callApplicationOnCreate办法中,代码如下:

/**
 * Perform calling of the application's {@link Application#onCreate}
 * method.  The default implementation simply calls through to that method.
 *
 * <p>Note: This method will be called immediately after {@link #onCreate(Bundle)}.
 * Often instrumentation tests start their test thread in onCreate(); you
 * need to be careful of races between these.  (Well between it and
 * everything else, but let's start here.)
 *
 * @param app The application being created.
 */
public void callApplicationOnCreate(Application app) {
    app.onCreate();
}

该办法直接履行了Application的onCreate办法,此刻咱们的程序现已算发动了。

前面流程先回顾一下

activity经过startActivity时,终究会调用到ActivityStackSupervisor—>startSpecificActivity() ,进程假如不存在,则去发动,假如进程存在,则会履行realStartActivityLocked()办法。

Android Framework之Activity启动流程

而在该办法中,咱们刚刚是看的进程未发动的流程,所以这个当地它是如何又回调的这个当地来的呢?咱们回到ActivityManagerService中的thread.bindApplication()代码节点持续往下走。

Android Framework之Activity启动流程

图片中红框一 调用了ATMS中的attachApplication() 办法。

红框二处是绑定服务的流程,先略过。

进入到ATMS中的attachApplication办法。

ATMS–>attachApplication();

RootWindowContainer –> attachApplication() — startActivityForAttachedApplicationIfNeeded();

Android Framework之Activity启动流程

进入到startActivityForAttachedApplicationIfNeede办法中。

private boolean startActivityForAttachedApplicationIfNeeded(ActivityRecord r,
        WindowProcessController app, ActivityRecord top) {
    if (r.finishing || !r.okToShowLocked() || !r.visibleIgnoringKeyguard || r.app != null
            || app.mUid != r.info.applicationInfo.uid || !app.mName.equals(r.processName)) {
        return false;
    }
    try {
        //此处回调了ActivityStackSupervisor中的realStartActivityLocked办法。
        if (mStackSupervisor.realStartActivityLocked(r, app,
                top == r && r.isFocusable() /*andResume*/, true /*checkConfig*/)) {
            mTmpBoolean = true;
        }
    } catch (RemoteException e) {
        Slog.w(TAG, "Exception in new application when starting activity "
                + top.intent.getComponent().flattenToShortString(), e);
        mTmpRemoteException = e;
        return true;
    }
    return false;
}

此处回调了ActivityStackSupervisor中的realStartActivityLocked办法。

ActivityStackSupervisor –> realStartActivityLocked();

这个当地就和前面形成了闭环,即发动activity时,先检查进程是否存在,假如存在,直接发动activity;假如不存在,去创立进程,进程创立成功后,再次发动activity。

咱们进入到realStartActivityLocked 看看activity是怎样发动的,它的生命周期又是如何回调的。

// 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),
// Schedule transaction.
mService.getLifecycleManager().scheduleTransaction(clientTransaction);

该办法中调用了ATMS中的getLifecycleManager办法,并终究调用了ClientLifecycleManager.scheduleTransaction()办法,并将ClientTransaction目标作为参数传递了进去。

留意:此处创立了ClientTransaction目标,并addCallBack(). LaunchActivityItem,这个LaunchActivityItem是ClientTransactionItem的子类,后面履行execut办法时会被回调到。

public void schedule() throws RemoteException {
    mClient.scheduleTransaction(this);
}

ClientLifecycleManager –> scheduleTransaction()

IApplicationThread –> scheduleTransaction()

ApplicationThread(ActivityThrad的内部类) –> scheduleTransaction()

ClientTransactionHandler(ActivitThread的父类) –> scheduleTransaction()


/** Prepare and schedule transaction for execution. */
void scheduleTransaction(ClientTransaction transaction) {
    transaction.preExecute(this);
    sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}

ActivityThread的handler中检查该音讯。

Android Framework之Activity启动流程

TransactionExecutor — > execute() –> executeCallbacks()

ClientTransactionItem –> execute() 调用其父类的execute办法。

LaunchActivityItem –> execute() .

ClientTransactionHandler –> handleLaunchActivity() 它只有一个子类,便是ActivityThread。

ActivityThread –> handleLaunchActivity() –> performLaunchActivity();

performLaunchActivity代码精简如下:

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    //反射创立activity类。
    ContextImpl appContext = createBaseContextForActivity(r);
    Activity activity = null;
    try {
        java.lang.ClassLoader cl = appContext.getClassLoader();
        activity = mInstrumentation.newActivity(
                cl, component.getClassName(), r.intent);
        StrictMode.incrementExpectedActivityCount(activity.getClass());
        r.intent.setExtrasClassLoader(cl);
        r.intent.prepareToEnterProcess();
        if (r.state != null) {
            r.state.setClassLoader(cl);
        }
    } catch (Exception e) {
        if (!mInstrumentation.onException(activity, e)) {
            throw new RuntimeException(
                "Unable to instantiate activity " + component
                + ": " + e.toString(), e);
        }
    }
    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 (activity != null) {      
        activity.mCalled = false;
        //履行Activity的onCreate办法。
        if (r.isPersistable()) {
            mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
        } else {
            mInstrumentation.callActivityOnCreate(activity, r.state);
        }
    }
    return activity;
}

其中先是反射创立了activity类,然后attach,终究经过Instumentation回调了Activity的onCreate办法。

Intrumentation –> callActivityOnCreate(); Activity –> onCreate();

mWindow = new PhoneWindow(this, window, activityConfigCallback);

attach办法便是赋值变量、然后给Activity创立一个视图窗口。

Activity.onCreate()被触发

在触发了Activity的onCreate的办法之后,整个Activity就算发动了,而Activity的发动流程也算是结束。

Activity的其他生命周期,如start、resume、restart等办法回调是在TransactionExecutor –execute()–> executeLifecycleState().这个和前面的executeCallbacks()触发流程根本差不多,这儿就不持续剖析了。

avtivity发动后都是在onResume界面才干看到画面,所以咱们独自看下onResume的触发流程。

TransactionExecutor–>executeLifecycleState()

ActivityLifecycleItem(父类的办法) –> execute

ResumeActivityItem –> handleResumeActivity()

ActivityThread –> handleResumeActivity();

if (r.activity.mVisibleFromClient) {
    r.activity.makeVisible();
}

Activity中的makeVisible办法如下:

void makeVisible() {
    if (!mWindowAdded) {
        ViewManager wm = getWindowManager();
        wm.addView(mDecor, getWindow().getAttributes());
        mWindowAdded = true;
    }
    mDecor.setVisibility(View.VISIBLE);
}

mDecor.setVisibility(View.VISIBLE);

mDecor.setVisibility(View.VISIBLE) 显现界面。

Activity发动全流程汇总

Activity –> startActivity()

Instrumentation —> execStartActivity

ActivityTaskManagerService –> startActivityAsUser()

ActivityStarter–execute()–> startActivityInner–》deliverToCurrentTopIfNeeded()

RootWindowContainer–》resumeFocusedStacksTopActivities

ActivityStack–>resumeTopActivityUncheckedLocked–>resumeTopActivityInnerLocked

ActivityStackSupervisor–》startSpecificActivity()

startSpecificActivity办法内有两种情况:

1、存在进程,直接做创立activity并发动等流程:ActivityStackSupervisor--》 realStartActivityLocked
2、不存在进程,创立进程,然后再次回调  realStartActivityLocked()。

先看进程没有的流程。

先从zygote发送进程创立的流程开端。

ActivityTaskManagerService–>startProcessAsync

ActivityManagerService–>startProcess–> startProcessLocked()

ProcessList–>startProcessLocked–>startProcessLocked()–>startProcess–>startProcess()–>createAppZygoteForProcessIfNeeded()去创立zygote目标

//在startProcesslocked会判断是否发动了app进程,假如发动了,直接回来,没有则去经过Zygote发送音讯的办法发动ActivitThread进程,

ZygoteProcess–>start()–>startViaZygote()–》zygoteSendArgsAndGetResult()

先树立localSocket链接,然后发送音讯,去创立ActivitThread,并调用main办法。
另外此处发送的音讯是什么要搞清楚?是processClass字段,值是 android.app.ActivityThread 

发送音讯成功后,咱们再看Zygote的接纳流程:

从zygote初始化走起。

ZygoteInit –>main()

ZygoteServer –> runSelectLoop() :

runSelectLoop敞开无限循环,一向读取localSocket的值。

ZygoteConnection –> processOneCommand()–> handleChildProc()

    try {
        //一向读取音讯,在前面发送“com.app.AcitityThread”音讯之后,这儿会受到此音讯。
        args = Zygote.readArgumentList(mSocketReader);
    } catch (IOException ex) {
        throw new IllegalStateException("IOException on command socket", ex);
    }

ZygoteInit –> childZygoteInit()

RuntimeInit–>findStaticMain() 经过反射调用class的main办法。

这儿便是Zygote的发送音讯、接纳音讯并创立ActivityThread且履行其main()办法的流程。


检查ActivityThread被创立之后的流程。

ActivityThread.main()

ActivityThread –> main()–>attach(false)

    attach传入的是false

IActivityManager –> attachApplication();

    IActivityManager此类是aidl接口,让ActivityThread和AMS直接通讯

ActivityManageService–> attachApplication()

ActivityThread–>bindApplication() –>sendMessage(H.BIND_APPLICATION, data)–>handleBindApplication()

    //handleBindApplication履行流程如下:
LoadedApk-->makeApplication()
Instumentation--> newApplication()
Application --> attach()-->attachBaseContext()
ContextWrapper -->attachBaseContext()

application和context都创立结束之后,持续履行ActivityThread 之后的代码。

ActivityThread–>callApplicationOnCreate()

public void callApplicationOnCreate(Application app) {
	app.onCreate();
}		

此处履行了Application的onCreate办法,咱们的程序现已发动

进程发动并履行onCreate办法之后,咱们回到ATMS持续履行之后的办法。

ATMS–>attachApplication();

RootWindowContainer –> attachApplication() — startActivityForAttachedApplicationIfNeeded();

ActivityStackSupervisor –> realStartActivityLocked();

   调用realStartActivityLocke()d和刚开端点击activity时的流程形成了闭环,即发动进程之后,再去履行发动Activity的流程。

咱们现在能够检查realStartActivityLocked()办法之后的流程。

ClientLifecycleManager –> scheduleTransaction()

IApplicationThread –> scheduleTransaction()

ApplicationThread(ActivityThrad的内部类) –> scheduleTransaction()

ClientTransactionHandler(ActivitThread的父类) –> scheduleTransaction()

TransactionExecutor — > execute() –> executeCallbacks()

ClientTransactionItem –> execute()

LaunchActivityItem –> execute()

ClientTransactionHandler –> handleLaunchActivity()

    ClientTransactionHandler它只有一个子类,便是ActivityThread。

ActivityThread –> handleLaunchActivity() –> performLaunchActivity();

    performLaunchActivity此处反射创立了activity类,然后attach,终究经过Instumentation回调了Activity的onCreate办法。

Activity.onCreate()被触发

至此Actiivty的发动流程现已结束。

终究咱们再看一下activity显现的流程。

avtivity发动后都是在onResume界面才干看到画面,所以咱们独自看下onResume的触发流程。

TransactionExecutor–>executeLifecycleState()

ActivityLifecycleItem(父类的办法) –> execute

ResumeActivityItem –> handleResumeActivity()

ActivityThread –> handleResumeActivity();

if (r.activity.mVisibleFromClient) {
	r.activity.makeVisible();
}
void makeVisible() {
	if (!mWindowAdded) {
		ViewManager wm = getWindowManager();
		wm.addView(mDecor, getWindow().getAttributes());
		mWindowAdded = true;
	}
	mDecor.setVisibility(View.VISIBLE);
}
mDecor.setVisibility(View.VISIBLE);

mDecor.setVisibility(View.VISIBLE);这个便是显出view的办法,VISIBLE之后,咱们的界面也能看到了。

发动时序总图

Android Framework之Activity启动流程

总结

Activity发动流程经过startActivity触发,会去检查进程是否发动,假如没有发动进程,会经过Zygote进程经过localSocket发送音讯,音讯的最关键信息是进程姓名:android.app.ActivityThread。

由于zygote敞开了无限循环检测,所以能够立马收到音讯,并反射创立咱们的ActivityThread类,并履行main办法。

ActivityThrad创立之后,会经过AMS中的attachApplication办法,创立Application,终究回到ActivityThread将application绑定context,终究履行Application的onCreate办法,app进程发动。

application发动之后再去发动activity。

发动activity终究会调用ActivityThread中的handleLaunchActivity办法,此办法调用之后会触发activity的onCreate办法,activity发动。

参考文章

blog.csdn.net/u013347784/…

【感谢】