Activity启动过程源码解析

分类: 其它 暂无人评论 carter 5月前发布

背景

启动App内部的Activity,Android 6.0 系统

概要

  1. 系统会为每个App创建一个进程,系统进程和App进程之间通过Binder通信
  2. 2个Binder接口 IActivityManager 和 IApplicationThread
  3. 几个Binder相关的类
    ActivityManagerService extends ActivityManagerNative
    ActivityManagerNative extends Binder implements IActivityManager
    (简称AMS)
    ApplicationThread extends ApplicationThreadNative
    ApplicationThreadNative extends Binder implements IApplicationThread
    (简称AT)
  4. App进程通知AMS启动Activity-->进入系统进程处理,通知上一个Activity的AT进行pause-->进入App进程,pause完成后,通知AMS-->进入系统进程处理,通知App的AT进行scheduleLaunchActivity --> 进入App进程,创建Activity对象,调用Activity.onCreate()、onStart()、onResume(),通知AMS-->进入系统进程处理,通知上一个App的AT进行stop

fQn3uodUNS6eZkPm.png

详细

----------App进程---------->
1) Activity.startActivity()-->startActivityForResult()

public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
    ...
    Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, this,
                intent, requestCode, options);
 }

注意第二个参数 mMainThread.getApplicationThread()

public final class ActivityThread {
    final ApplicationThread mAppThread = new ApplicationThread();
    public ApplicationThread getApplicationThread(){
        return mAppThread;
    }
}

mMainThread就是ActivityThread,持续跟踪 mMainThread.mAppThread

2) Instrumentation.execStartActivity()

public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, Activity target,
        Intent intent, int requestCode, Bundle options) {
    IApplicationThread whoThread = (IApplicationThread) contextThread;
    ...
    try {
        ...
        int result = ActivityManagerNative.getDefault()
            .startActivity(whoThread, who.getBasePackageName(), intent,
                    intent.resolveTypeIfNeeded(who.getContentResolver()),
                    token, target != null ? target.mEmbeddedID : null,
                    requestCode, 0, null, options);
        ...
    } catch (RemoteException e) {
        throw new RuntimeException("Failure from system", e);
    }
    return null;
}

继续跟踪 mMainThread.mAppThread,whoThread就是它

3) ActivityManagerNative.getDefault().startActivity()

public abstract class ActivityManagerNative extends Binder implements IActivityManager {
    class ActivityManagerProxy implements IActivityManager
    {
        public ActivityManagerProxy(IBinder remote)
        {
            mRemote = remote;
        }
        public IBinder asBinder()
        {
            return mRemote;
        }
        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.writeStrongBinder(caller != null ? caller.asBinder() : null);
            ...
            mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
            ...
            return result;
        }
    }
}

HNXld1ehSIAQdKb2.png

继续跟踪 mMainThread.mAppThread,caller就是它,被传到 mRemote 的方法里了

App进程通知系统进程都是通过ActivityManagerNative

----------系统进程---------->
4) ActivityManagerService.startActivity()

@Override
public final int startActivity(...) {
    return startActivityAsUser(...);
}
@Override
public final int startActivityAsUser(...) {
    ...
    return mStackSupervisor.startActivityMayWait(...);
}

5) ActivityStackSupervisor.startActivityMayWait()
加工将要启动的Activity的相关信息

6) ActivityStack.startPausingLocked()
在 launchActivity 之前先pause上一个Activity,prev.app 表明不仅限于当前APP

wiPTvggQnTSKcJre.png

7) ActivityStackSupervisor.realStartActivityLocked()

final boolean realStartActivityLocked(ActivityRecord r,
        ProcessRecord app, boolean andResume, boolean checkConfig)
        throws RemoteException {
        ...
        app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
                new Configuration(stack.mOverrideConfig), r.compat, r.launchedFromPackage,
                task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
                newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);
        ...
    } catch (RemoteException e) {
        ...
        throw e;
    }
    ...
    return true;
}

上面跟踪App进程里的 mMainThread.mAppThread 那么久,终于在这里再现身影,app.thread 就是它的Binder接口

系统进程通知App进程都是通过ApplicationThreadNative

红框标示 ActivityManagerService.activityPaused() 说明App进程pause activity完成了

ru4tchdXAzbmO1fr.png

8) ApplicationThreadNative.scheduleLaunchActivity()

public abstract class ApplicationThreadNative extends Binder implements IApplicationThread {
    class ApplicationThreadProxy implements IApplicationThread {
        private final IBinder mRemote;
        public final void scheduleLaunchActivity() throws RemoteException {
            ...
            mRemote.transact(SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION, data, null, IBinder.FLAG_ONEWAY);
            ...
        }
    }
}

----------App进程---------->
9) ApplicationThreadNative

public abstract class ApplicationThreadNative extends Binder implements IApplicationThread {
    @Override
    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
        throws RemoteException {    
        switch (code) {
            ...
            case SCHEDULE_PAUSE_ACTIVITY_TRANSACTION: {
                ...
            }
            case SCHEDULE_STOP_ACTIVITY_TRANSACTION: {
                ...
            }
            case SCHEDULE_RESUME_ACTIVITY_TRANSACTION: {
                ...
            }
            case SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION: {
                ...
                scheduleLaunchActivity(intent, b, ident, info, curConfig, overrideConfig, compatInfo,
                referrer, voiceInteractor, procState, state, persistentState, ri, pi,
                notResumed, isForward, profilerInfo);
                return true;
            }
            case SCHEDULE_NEW_INTENT_TRANSACTION: {
                ...
            }
            case SCHEDULE_FINISH_ACTIVITY_TRANSACTION: {
                ...
            }
            case SCHEDULE_CREATE_SERVICE_TRANSACTION: {
                ...
            }
            case SCHEDULE_BIND_SERVICE_TRANSACTION: {
                ...
            }
            case SCHEDULE_UNBIND_SERVICE_TRANSACTION: {
                ...
            }
            ...
            return super.onTransact(code, data, reply, flags);
        }
    }
}

10) ActivityThread.ApplicationThread.scheduleLaunchActivity()

public final class ActivityThread {
    final ApplicationThread mAppThread = new ApplicationThread();
    final H mH = new H();
    private class ApplicationThread extends ApplicationThreadNative {
        ...
        public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
            ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
            CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
            int procState, Bundle state, PersistableBundle persistentState,
            List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
            boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
            ...
            sendMessage(H.LAUNCH_ACTIVITY, r);
        }
    }
    private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        msg.arg1 = arg1;
        msg.arg2 = arg2;
        ...
        mH.sendMessage(msg);
    }
}

mH是什么

11) ActivityThread.H

private class H extends Handler {
    public static final int LAUNCH_ACTIVITY         = 100;
    public static final int PAUSE_ACTIVITY          = 101;
    public static final int PAUSE_ACTIVITY_FINISHING= 102;
    public static final int STOP_ACTIVITY_SHOW      = 103;
    public static final int STOP_ACTIVITY_HIDE      = 104;
    public static final int SHOW_WINDOW             = 105;
    public static final int HIDE_WINDOW             = 106;
    public static final int RESUME_ACTIVITY         = 107;
    public static final int SEND_RESULT             = 108;
    public static final int DESTROY_ACTIVITY        = 109;
    public static final int BIND_APPLICATION        = 110;
    public static final int EXIT_APPLICATION        = 111;
    public static final int NEW_INTENT              = 112;
    public static final int RECEIVER                = 113;
    public static final int CREATE_SERVICE          = 114;
    public static final int SERVICE_ARGS            = 115;
    public static final int STOP_SERVICE            = 116;
    public static final int CONFIGURATION_CHANGED   = 118;
    public static final int CLEAN_UP_CONTEXT        = 119;
    public static final int GC_WHEN_IDLE            = 120;
    public static final int BIND_SERVICE            = 121;
    public static final int UNBIND_SERVICE          = 122;
    public static final int DUMP_SERVICE            = 123;
    public static final int LOW_MEMORY              = 124;
    public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
    public static final int RELAUNCH_ACTIVITY       = 126;
    public static final int PROFILER_CONTROL        = 127;
    public static final int CREATE_BACKUP_AGENT     = 128;
    public static final int DESTROY_BACKUP_AGENT    = 129;
    public static final int SUICIDE                 = 130;
    public static final int REMOVE_PROVIDER         = 131;
    public static final int ENABLE_JIT              = 132;
    public static final int DISPATCH_PACKAGE_BROADCAST = 133;
    public static final int SCHEDULE_CRASH          = 134;
    public static final int DUMP_HEAP               = 135;
    public static final int DUMP_ACTIVITY           = 136;
    public static final int SLEEPING                = 137;
    public static final int SET_CORE_SETTINGS       = 138;
    public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
    public static final int TRIM_MEMORY             = 140;
    public static final int DUMP_PROVIDER           = 141;
    public static final int UNSTABLE_PROVIDER_DIED  = 142;
    public static final int REQUEST_ASSIST_CONTEXT_EXTRAS = 143;
    public static final int TRANSLUCENT_CONVERSION_COMPLETE = 144;
    public static final int INSTALL_PROVIDER        = 145;
    public static final int ON_NEW_ACTIVITY_OPTIONS = 146;
    public static final int CANCEL_VISIBLE_BEHIND = 147;
    public static final int BACKGROUND_VISIBLE_BEHIND_CHANGED = 148;
    public static final int ENTER_ANIMATION_COMPLETE = 149;
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case LAUNCH_ACTIVITY: {
                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
                final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
                r.packageInfo = getPackageInfoNoCheck(
                        r.activityInfo.applicationInfo, r.compatInfo);
                handleLaunchActivity(r, null);
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            } break;
            ...
            case PAUSE_ACTIVITY:
                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
                handlePauseActivity((IBinder)msg.obj, false, (msg.arg1&1) != 0, msg.arg2,
                        (msg.arg1&2) != 0);
                maybeSnapshot();
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                break;
            case RESUME_ACTIVITY:
                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
                handleResumeActivity((IBinder) msg.obj, true, msg.arg1 != 0, true);
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                break;
              ...
              ...
        }
    }
 }

看到这里,可以知道
管理Activity都是通过Handler.sendMessage()

要知道Handler都是和Looper配对使用的,新建Handler前,都需要初始化Looper,那Looper在哪

12) ActivityThread.main()

public static void main(String[] args) {
    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
    SamplingProfilerIntegration.start();
    // 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();
    // Set the reporter for event logging in libcore
    EventLogger.setReporter(new EventLoggingReporter());
    AndroidKeyStoreProvider.install();
    // 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);
    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }
    if (false) {
        Looper.myLooper().setMessageLogging(new
                LogPrinter(Log.DEBUG, "ActivityThread"));
    }
    // End of event ActivityThreadMain.
    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

重点是这三句

Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread(); //内部 H mH = new H();
Looper.loop();

如果不清楚Handler和Looper可以参考Handler和Looper解析

第一次启动App的时候,App还没有自己的进程,系统会创建一个新的进程,新的进程会导入android.app.ActivityThread,并且执行main()

main()方法里Looper.loop()死循环取消息(管理Activity、Service...的消息),其他线程传输消息到main线程都是通过ActivityThread.mH.sendMessage()

13) 回到 10) 里面的 sendMessage(H.LAUNCH_ACTIVITY, r)
--> 11) 里面的 handleLaunchActivity(r, null)

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    ...
    WindowManagerGlobal.initialize();
    ...
    Activity a = performLaunchActivity(r, customIntent);
    ...
    handleResumeActivity(r.token, false, r.isForward,!r.activity.mFinished && !r.startsNotResumed);
    ...
}
 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    ...
    Activity activity = null;
    java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
    activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);//反射
    ...
    if (r.isPersistable()) {
        mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
    } else {
        mInstrumentation.callActivityOnCreate(activity, r.state);
    }
    ...
    if (!r.activity.mFinished) {
        activity.performStart();
        r.stopped = false;
    }
    ...
    return activity;
}

mInstrumentation.callActivityOnCreate()-->activity.performCreate()-->onCreate()

handleLaunchActivity()内部先执行performLaunchActivity()再执行handleResumeActivity()
performLaunchActivity()内部会先执行mInstrumentation.callActivityOnCreate()再执行activity.performStart()

至此,Activity执行了onCreate()-->onStart()-->onResume(),在App内部启动完毕。

14) handleResumeActivity()

final void handleResumeActivity(IBinder token,
        boolean clearHide, boolean isForward, boolean reallyResume) {
    ...
    ActivityClientRecord r = performResumeActivity(token, clearHide);
    ...
    try {
        ActivityManagerNative.getDefault().activityResumed(token);
    } catch (RemoteException ex) {
    }
    ...
}

执行完onResume()通知AMS,系统进程就会接着去stop上一个Activity

总结

从上面的时序图也可以观察到

  1. Activity要通知系统进程,总是
    Activity-->Instrumentation-->ActivityManagerNative-->
    进入系统进程
    ActivityManagerNative-->ActivityManagerService-->ActivityStackSupervisor/ActivityStack
  2. 系统进程要管理Activity,总是
    ApplicationThreadNative-->
    进入App进程
    ApplicationThreadNative-->ActivityThread.ApplicationThread-->ActivityThread.H-->Instrumentation-->Activity
  3. Activity A 启动 Activity B
    生命周期相关的整个过程是:a.onPause()-->b.onCreate()-->b.onStart()-->b.onResume()-->a.onStop()

如何debug SDK源码

  1. 使用模拟器,选Nexus系列
  2. 下载源码

    QhH0l5pSCMvuItaq.png

  3. 勾选Show all processes

    yZ8eoKmbi81TiUu4.png

  4. 选择system_process

    T6bf4uiuXMKPLJ22.png

  5. OK

标签:
本文系转载文章,感谢原作者的辛勤付出!
交流QQ群:32261424
Previous:
Next:
没有了

发表评论

,将以游客形式发表

网友最新评论(0)