Activity(一)启动过程

背景

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

概要

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

详细

----------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

  1. 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就是它

  1. 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;
        }
    }
}

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

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

----------系统进程---------->

  1. ActivityManagerService.startActivity()
@Override
public final int startActivity(...) {
    return startActivityAsUser(...);
}

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

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

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

  1. 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完成了

  1. 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进程---------->

  1. 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);
        }
    }
}
  1. 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是什么

  1. 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在哪

  1. 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()

  1. 回到 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内部启动完毕。

  1. 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. 下载源码


  3. 勾选Show all processes


  4. 选择system_process


  5. OK
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,547评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,399评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,428评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,599评论 1 274
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,612评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,577评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,941评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,603评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,852评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,605评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,693评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,375评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,955评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,936评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,172评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,970评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,414评论 2 342

推荐阅读更多精彩内容