是谁拨动了你的Activity

谁启动了你的activity ?

首先抛出一个问题,当你点击桌面应用图标的时候,你的Launch-Activity的oncreate方式是被谁调用起来的,才会执行到经过了哪些流程才到Activity类的oncreate方法里的?

要回答上面这个问题首先需要了解到 应用的启动流程,app的启动流程大致可以同如下的流程概括
Activity 启动流程
  • 当前我们点击launch中某个的app图标时,Launcher进程采用Binder IPC向system_server进程发起startActivity请求
  • 这个时候 system_server收到消息之后 就向zygote进程发送fork一个子进程的请求,这个进程就是你的App进程,
  • App进程,通过Binder IPC向sytem_server进程发起attachApplication请求,
  • system_server收到请求之后,进行一系列准备工作后就向App进程发送了scheduledLaunch Activity的命令,
  • App进程的ApplicationThread收到消息后向ActivityThread 发送launchactivity的命令,
  • 主线程在收到Message后,通过发射机制创建目标Activity,并回调Activity.onCreate()等方法。

所以主要启动工作都在ActivityThread.java 这个类里面。

Activty Pause又是怎样的流程 ?

首先要说一下 Binder 和handler ,Bindle 是用于不同进程间的通信使用,由一个binder的客户端向另一个进程的服务端发送请求;而handler是同一个进程下面不同线程的通信,比如我们经常用到的子线程向主线程通知更新ui都是通过handler的方式,看下图
暂停Activity
  • 当我们的activty进入后台时线程1 ActivtyManagerService(具体Home进入后台是怎么通知到ActivtyManagerService的后面再研究)通过handler通知到线程2 ApplicationThreadProxy,因为是同一个进程里面所以通过handler,
  • ApplicationThreadProxy 通过binder方式将暂停activity消息通知到了线程4 ApplicationThread,
  • 线程4通过handler消息机制,将暂停Activity的消息发送给主线程;
  • 主线程在looper.loop()中循环遍历消息,当收到暂停Activity的消息(PAUSE_ACTIVITY)时,便将消息分发给ActivityThread.H.handleMessage()方法,再经过方法的层层调用,最后便会调用到Activity.onPause()方法。

现在看看 android源码里面是怎样的

通过上面的流程图我们知道 启动 activty ,首先是ApplicationThreadProxy发送了Schedule LaunchActivity 消息,ApplicationThread 是ActivityThread 的一个内部类:


  final ApplicationThread mAppThread = new ApplicationThread();
private class ApplicationThread extends ApplicationThreadNative {
       private static final String DB_INFO_FORMAT = "  %8s %8s %14s %14s  %s";

       private int mLastProcessState = -1;

       // we use token to identify this activity without having to send the
       // activity itself back to the activity manager. (matters more with ipc)
       @Override
       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) {

           updateProcessState(procState, false);

           ActivityClientRecord r = new ActivityClientRecord();

           r.token = token;
           r.ident = ident;
           r.intent = intent;
           r.referrer = referrer;
           r.voiceInteractor = voiceInteractor;
           r.activityInfo = info;
           r.compatInfo = compatInfo;
           r.state = state;
           r.persistentState = persistentState;

           r.pendingResults = pendingResults;
           r.pendingIntents = pendingNewIntents;

           r.startsNotResumed = notResumed;
           r.isForward = isForward;

           r.profilerInfo = profilerInfo;

           r.overrideConfig = overrideConfig;
           updatePendingConfiguration(curConfig);

           sendMessage(H.LAUNCH_ACTIVITY, r);
       }

      ......

看到上面代码 sendMessage(H.LAUNCH_ACTIVITY, r); 他发了消息出去 所以找实现handleMessage的地方:

 private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        // If we are getting ready to gc after going to the background, well
        // we are back active so skip it.
        unscheduleGcIdler();
        mSomeActivitiesChanged = true;

        if (r.profilerInfo != null) {
            mProfiler.setProfiler(r.profilerInfo);
            mProfiler.startProfiling();
        }

        // Make sure we are running with the most recent config.
        handleConfigurationChanged(null, null);

        if (localLOGV) Slog.v(
            TAG, "Handling launch of " + r);

        // Initialize before creating the activity
        WindowManagerGlobal.initialize();

        Activity a = performLaunchActivity(r, customIntent);

        if (a != null) {
            r.createdConfig = new Configuration(mConfiguration);
            Bundle oldState = r.state;
            handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed);

            if (!r.activity.mFinished && r.startsNotResumed) {
                // The activity manager actually wants this one to start out
                // paused, because it needs to be visible but isn't in the
                // foreground.  We accomplish this by going through the
                // normal startup (because activities expect to go through
                // onResume() the first time they run, before their window
                // is displayed), and then pausing it.  However, in this case
                // we do -not- need to do the full pause cycle (of freezing
                // and such) because the activity manager assumes it can just
                // retain the current state it has.
                try {
                    r.activity.mCalled = false;
                    mInstrumentation.callActivityOnPause(r.activity);
                    // We need to keep around the original state, in case
                    // we need to be created again.  But we only do this
                    // for pre-Honeycomb apps, which always save their state
                    // when pausing, so we can not have them save their state
                    // when restarting from a paused state.  For HC and later,
                    // we want to (and can) let the state be saved as the normal
                    // part of stopping the activity.
                    if (r.isPreHoneycomb()) {
                        r.state = oldState;
                    }
                    if (!r.activity.mCalled) {
                        throw new SuperNotCalledException(
                            "Activity " + r.intent.getComponent().toShortString() +
                            " did not call through to super.onPause()");
                    }

                } catch (SuperNotCalledException e) {
                    throw e;

                } catch (Exception e) {
                    if (!mInstrumentation.onException(r.activity, e)) {
                        throw new RuntimeException(
                                "Unable to pause activity "
                                + r.intent.getComponent().toShortString()
                                + ": " + e.toString(), e);
                    }
                }
                r.paused = true;
            }
        } else {
            // If there was an error, for any reason, tell the activity
            // manager to stop us.
            try {
                ActivityManagerNative.getDefault()
                    .finishActivity(r.token, Activity.RESULT_CANCELED, null, false);
            } catch (RemoteException ex) {
                // Ignore
            }
        }
}    

看到了 中间会 handleConfigurationChanged 等配置,(这个操作就对应我们activty的 onConfigurationChanged():方法)然后就是 performLaunchActivity,在看看这个方法里面干了什么事,看它的返回值是个activity ,难道是解析manifest xml信息找到我们的launch的activity呢?继续往下看吧,

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");

        ActivityInfo aInfo = r.activityInfo;
        if (r.packageInfo == null) {
            r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                    Context.CONTEXT_INCLUDE_CODE);
        }

        ComponentName component = r.intent.getComponent();
        if (component == null) {
            component = r.intent.resolveActivity(
                mInitialApplication.getPackageManager());
            r.intent.setComponent(component);
        }

        if (r.activityInfo.targetActivity != null) {
            component = new ComponentName(r.activityInfo.packageName,
                    r.activityInfo.targetActivity);
        }

        Activity activity = null;
        try {
            java.lang.ClassLoader cl = r.packageInfo.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);
            }
        }

        try {
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);

            if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
            if (localLOGV) Slog.v(
                    TAG, r + ": app=" + app
                    + ", appName=" + app.getPackageName()
                    + ", pkg=" + r.packageInfo.getPackageName()
                    + ", comp=" + r.intent.getComponent().toShortString()
                    + ", dir=" + r.packageInfo.getAppDir());

            if (activity != null) {
                Context appContext = createBaseContextForActivity(r, activity);
                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config = new Configuration(mCompatConfiguration);
                if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
                        + r.activityInfo.name + " with config " + config);
                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);

                if (customIntent != null) {
                    activity.mIntent = customIntent;
                }
                r.lastNonConfigurationInstances = null;
                activity.mStartedActivity = false;
                int theme = r.activityInfo.getThemeResource();
                if (theme != 0) {
                    activity.setTheme(theme);
                }

                activity.mCalled = false;
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                if (!activity.mCalled) {
                    throw new SuperNotCalledException(
                        "Activity " + r.intent.getComponent().toShortString() +
                        " did not call through to super.onCreate()");
                }
                r.activity = activity;
                r.stopped = true;
                if (!r.activity.mFinished) {
                    activity.performStart();
                    r.stopped = false;
                }
                if (!r.activity.mFinished) {
                    if (r.isPersistable()) {
                        if (r.state != null || r.persistentState != null) {
                            mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
                                    r.persistentState);
                        }
                    } else if (r.state != null) {
                        mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
                    }
                }
                if (!r.activity.mFinished) {
                    activity.mCalled = false;
                    if (r.isPersistable()) {
                        mInstrumentation.callActivityOnPostCreate(activity, r.state,
                                r.persistentState);
                    } else {
                        mInstrumentation.callActivityOnPostCreate(activity, r.state);
                    }
                    if (!activity.mCalled) {
                        throw new SuperNotCalledException(
                            "Activity " + r.intent.getComponent().toShortString() +
                            " did not call through to super.onPostCreate()");
                    }
                }
            }
            r.paused = true;

            mActivities.put(r.token, r);

        } catch (SuperNotCalledException e) {
            throw e;

        } catch (Exception e) {
            if (!mInstrumentation.onException(activity, e)) {
                throw new RuntimeException(
                    "Unable to start activity " + component
                    + ": " + e.toString(), e);
            }
        }
        return activity;
    }

从源码里面看到了

activity = mInstrumentation.newActivity( cl, component.getClassName(), r.intent);
//下面还有 看到了,
 mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);

上面这个地方获取了activity实例,我们先看看application的实例,因为我们每个应用都是有一个application的,先启动application再是activity才对的,

Application app = r.packageInfo.makeApplication(false, mInstrumentation); 

得到了application 实例,
那么 application的oncreate在哪里调到的呢,我们进到makeApplication 方法里面看下:


    public Application makeApplication(boolean forceDefaultAppClass,
            Instrumentation instrumentation) {
        if (mApplication != null) {
            return mApplication;
        }

        Application app = null;

        String appClass = mApplicationInfo.className;
        if (forceDefaultAppClass || (appClass == null)) {
            appClass = "android.app.Application";
        }

        try {
            java.lang.ClassLoader cl = getClassLoader();
            if (!mPackageName.equals("android")) {
                initializeJavaContextClassLoader();
            }
            ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
            app = mActivityThread.mInstrumentation.newApplication(
                    cl, appClass, appContext);
            appContext.setOuterContext(app);
        } catch (Exception e) {
            if (!mActivityThread.mInstrumentation.onException(app, e)) {
                throw new RuntimeException(
                    "Unable to instantiate application " + appClass
                    + ": " + e.toString(), e);
            }
        }
        mActivityThread.mAllApplications.add(app);
        mApplication = app;

        if (instrumentation != null) {
            try {
                instrumentation.callApplicationOnCreate(app);
            } catch (Exception e) {
                if (!instrumentation.onException(app, e)) {
                    throw new RuntimeException(
                        "Unable to create application " + app.getClass().getName()
                        + ": " + e.toString(), e);
                }
            }
        }

        // Rewrite the R 'constants' for all library apks.
        SparseArray<String> packageIdentifiers = getAssets(mActivityThread)
                .getAssignedPackageIdentifiers();
        final int N = packageIdentifiers.size();
        for (int i = 0; i < N; i++) {
            final int id = packageIdentifiers.keyAt(i);
            if (id == 0x01 || id == 0x7f) {
                continue;
            }

            rewriteRValues(getClassLoader(), packageIdentifiers.valueAt(i), id);
        }

        return app;
    }

看到有 instrumentation.callApplicationOnCreate(app); instrumentation 这个东东发起了 oncreate,那我们进去看下:

 /**
     * 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,这个app就是你自己的额application了,
然后在回到
mInstrumentation.callActivityOnCreate(activity, r.state);
继续看下 callActivityOnCreate实现

/**
     * Perform calling of an activity's {@link Activity#onCreate}
     * method.  The default implementation simply calls through to that method.
     *
     * @param activity The activity being created.
     * @param icicle The previously frozen state (or null) to pass through to onCreate().
     */
    public void callActivityOnCreate(Activity activity, Bundle icicle) {
        prePerformCreate(activity);
        activity.performCreate(icicle);
        postPerformCreate(activity);
    }

然后就进到了 Activity 里面了:

 final void performCreate(Bundle icicle) {
        onCreate(icicle);
        mActivityTransitionState.readState(icicle);
        performCreateCommon();
    }

之后 activity就调用了自己的onCreate。
哦,原来onCreate 是自己调用的,instrumentation 只是调用了performCreate而已,所以以后要是有人问你,是谁调用了 activty的onCreate,你就大声的告诉他,是activity他自己。
所以是谁启动了activity 那么你可以回到答是instrumentation 这个类,但是完成这个工作是在ActivityThread 这个线程里面来实现的。

不过ActivityThread 也是ApplicationThread 通过handler发消息给它,它才知道执行那个阶段的流程,而ApplicationThread 是 ApplicationThreadProxy 通过binder消息得到的,而 ApplicationThreadProxy 是ActivityMangerService 告诉它的,所以源头应该是ActivityMangerService 来控制。执行oncreate还是onpause的。

ActivityThread.handleLaunchActivity
    ->ActivityThread.handleConfigurationChanged
        ->ActivityThread.performConfigurationChanged
            ->ComponentCallbacks2.onConfigurationChanged

    ActivityThread.performLaunchActivity
        ->LoadedApk.makeApplication
            ->Instrumentation.callApplicationOnCreate
                ->Application.onCreate
    
        Instrumentation.callActivityOnCreate
            ->Activity.performCreate
                ->Activity.onCreate

        Instrumentation.callActivityonRestoreInstanceState
            ->Activity.performRestoreInstanceState
                ->Activity.onRestoreInstanceState

    ActivityThread.handleResumeActivity
        ->ActivityThread.performResumeActivity
            ->Activity.performResume
                ->Activity.performRestart
                    ->Instrumentation.callActivityOnRestart
                        ->Activity.onRestart

                    Activity.performStart
                        ->Instrumentation.callActivityOnStart
                            ->Activity.onStart

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

推荐阅读更多精彩内容