從Android源碼分析Activity加載流程

概述:startActivity->startActivityForResult->Instrumentation::execStartActivity->scheduleLaunchActivity->performLaunchActivity->handleLaunchActivity->handleResumeActivity

本文通過Android源碼介紹Activity的加載過程许蓖。首先從Activity.java中的startActivity開始:

@Override
public void startActivity(Intent intent, @Nullable Bundle options) {    
    if (options != null) {        
        startActivityForResult(intent, -1, options);    
    } else {                   
        startActivityForResult(intent, -1);    
    }
}

可以看出startActivity也是通過調用startActivityForResult實現(xiàn)的熟妓,接下來就研究startActivityForResult的實現(xiàn)兴枯。

Activity.java

@Override
public void startActivityForResult(String who, Intent intent, int requestCode, @Nullable Bundle options) {    
    Uri referrer = onProvideReferrer();    
    if (referrer != null) {        
        intent.putExtra(Intent.EXTRA_REFERRER, referrer);    
    }    

    Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity( 
        this, 
        mMainThread.getApplicationThread(), 
        mToken, 
        who,            
        intent, 
        requestCode, 
        options);    
    if (ar != null) {        
        mMainThread.sendActivityResult(mToken, who, requestCode, ar.getResultCode(), ar.getResultData());
    }    

    cancelInputsAndStartExitTransition(options);
}

這里通過Instrumentation類的execStartActivity方法來啟動Activity。

Instrumentation.java

public ActivityResult execStartActivity(        
    Context who, 
    IBinder contextThread, 
    IBinder token, 
    Activity target,        
    Intent intent, 
    int requestCode, 
    Bundle options) {    
    IApplicationThread whoThread = (IApplicationThread) contextThread;    
    Uri referrer = target != null ? target.onProvideReferrer() : null;    
    if (referrer != null) {        
        intent.putExtra(Intent.EXTRA_REFERRER, referrer);    
    }    

    if (mActivityMonitors != null) {        
        synchronized (mSync) {            
            final int N = mActivityMonitors.size();            
            for (int i=0; i<N; i++) {                
                final ActivityMonitor am = mActivityMonitors.get(i);                
                if (am.match(who, null, intent)) {                    
                    am.mHits++;                    
                    if (am.isBlocking()) {                        
                        return requestCode >= 0 ? am.getResult() : null;                                      
                    }                    
                    break;                
                }            
            }        
        }    
    }    

    try {        
        intent.migrateExtraStreamToClipData();        
        intent.prepareToLeaveProcess();        
        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;
}

whoThread是一個實現(xiàn)了IApplicationThread接口的類的實例,IApplicationThread接口提供了系統(tǒng)跟應用(application)交互的API,當應用啟動的時候踏施,application將實現(xiàn)了IApplicationThread接口的實例傳入Activity Manager,Activity Manager通過該實例指導應用進行諸如啟動罕邀、暫停畅形、停止Activity等一系列操作。

public interface IApplicationThread extends IInterface {    
    void schedulePauseActivity(IBinder token, boolean finished, boolean userLeaving,  
        int configChanges, boolean dontReport) throws RemoteException;        
    void scheduleStopActivity(IBinder token, boolean showWindow,  int configChanges) throws RemoteException;    
    void scheduleWindowVisibility(IBinder token, boolean showWindow) throws RemoteException;    
    void scheduleSleeping(IBinder token, boolean sleeping) throws RemoteException;    
    void scheduleResumeActivity(IBinder token, int procState, boolean isForward, Bundle resumeArgs) throws RemoteException;    
    void scheduleSendResult(IBinder token, List<ResultInfo> results) throws RemoteException;
    void scheduleLaunchActivity(.....);
    void scheduleRelaunchActivity(......);
    void scheduleDestroyActivity(......);
    ...
}

其中啟動Activity的函數(shù)是scheduleLaunchActivity,該函數(shù)的實現(xiàn)在ActivityThread類的一個私有類ApplicationThread里:
ActivityThread.java

public final class ActivityThread {
    ...
    private class ApplicationThread extends ApplicationThreadNative {
        @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);
    }
    ...
}

其中ApplicationThreadNative實現(xiàn)了IApplicationThread接口:

public abstract class ApplicationThreadNative extends Binder  
implements IApplicationThread {
    ...  
}

在ApplicationThread中我們看到scheduleLaunchActivity的實現(xiàn)燃少,該函數(shù)參數(shù)眾多束亏,包括傳入Activity的intent,標識該Activity的token阵具,存儲AndroidManifest.xml中<activity>和<receiver>標記段信息的activityInfo碍遍,存儲系統(tǒng)級別和用戶級別的配置curConfig(如屏幕方向,當前國家和字體縮放設置等阳液,通過getResources().getConfiguration()獲得)等怕敬。
將這些參數(shù)賦值給ActivityClientRecord,然后通過sendMessage發(fā)送一個類型為LAUNCH_ACTIVITY的message帘皿。
我們看看sendMessage的實現(xiàn):

ActivityThread.java

private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {    
    if (DEBUG_MESSAGES) 
        Slog.v(TAG, "SCHEDULE " + what + " " + mH.codeToString(what) + ": " + arg1 + " / " + obj);    
    Message msg = Message.obtain();    
    msg.what = what;    
    msg.obj = obj;    
    msg.arg1 = arg1;    
    msg.arg2 = arg2;    
    if (async) {        
        msg.setAsynchronous(true);    
    }    
    mH.sendMessage(msg);
}

sendMessage就是構造了一個Message并通過H類型的Handler發(fā)送出去东跪。看看H的定義:

ActivityThread.java

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 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 RELAUNCH_ACTIVITY: {            
            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityRestart");            
            ActivityClientRecord r = (ActivityClientRecord)msg.obj;            
            handleRelaunchActivity(r);            
            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);        
            }
            break;
            ...
        }
    }
    ...
}

在H類型的Handler里處理了各種類型的消息鹰溜,通過函數(shù)handleLaunchActivity處理LAUNCH_ACTIVITY消息:

ActivityThread.java

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    ...
    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) {
            try {    
                r.activity.mCalled = false;    
                mInstrumentation.callActivityOnPause(r.activity);
                ...
            }
          ...
        }
    } else {
        ...
    }
}

這里面主要包括三個操作虽填,performLaunchActivity啟動Activity,handleResumeActivity來Resume Activity曹动,最后通過Instrumentation的callActivityOnPause函數(shù)來OnPause Activity斋日。
來看看performLaunchActivity的實現(xiàn):

ActivityThread.java

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    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 (activity != null) {            
            Context appContext = createBaseContextForActivity(r, activity);            
            CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());            
            Configuration config = new Configuration(mCompatConfiguration);            
            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;
}

首先通過java.lang.ClassLoader,調用Instrumentation的newActivity方法墓陈,根據(jù)Activity的名稱加載Activity類:

Instrumentation.java

public Activity newActivity(ClassLoader cl, String className, Intent intent)        
    throws InstantiationException, IllegalAccessException, ClassNotFoundException {    
        return (Activity)cl.loadClass(className).newInstance();
}

然后通過createBaseContextForActivity生成Activity的context恶守,并通過activity.attach方法將Activity的context和其他屬性賦給Activity第献。接著調用Instrumentation的 callActivityOnCreate方法, callActivityOnRestoreInstanceState 方法和callActivityOnPostCreate 方法兔港, 分別對應Activity的onCreate庸毫,onRestoreInstanceState和onPostCreate方法。這樣就在performLaunchActivity函數(shù)中完成了Activity的加載和初始化過程衫樊。

回到handleLaunchActivity函數(shù)飒赃,在performLaunchActivity完成后,通過handleResumeActivity方法使得Activity完成onResume的準備工作科侈,進入onResume狀態(tài)盒揉。最后,調用Instrumentation的callActivityOnPause方法兑徘,使得Activity進入onPause的狀態(tài),這樣羡洛,當Activity最終展示出來的時候挂脑,就會從onResume作為開始。至此欲侮,Activity加載完畢崭闲。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市威蕉,隨后出現(xiàn)的幾起案子刁俭,更是在濱河造成了極大的恐慌,老刑警劉巖韧涨,帶你破解...
    沈念sama閱讀 212,454評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件牍戚,死亡現(xiàn)場離奇詭異穆趴,居然都是意外死亡窥翩,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,553評論 3 385
  • 文/潘曉璐 我一進店門常熙,熙熙樓的掌柜王于貴愁眉苦臉地迎上來娩贷,“玉大人第晰,你說我怎么就攤上這事”蜃妫” “怎么了茁瘦?”我有些...
    開封第一講書人閱讀 157,921評論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長储笑。 經常有香客問我甜熔,道長,這世上最難降的妖魔是什么南蓬? 我笑而不...
    開封第一講書人閱讀 56,648評論 1 284
  • 正文 為了忘掉前任纺非,我火速辦了婚禮哑了,結果婚禮上,老公的妹妹穿的比我還像新娘烧颖。我一直安慰自己弱左,他們只是感情好,可當我...
    茶點故事閱讀 65,770評論 6 386
  • 文/花漫 我一把揭開白布炕淮。 她就那樣靜靜地躺著拆火,像睡著了一般。 火紅的嫁衣襯著肌膚如雪涂圆。 梳的紋絲不亂的頭發(fā)上们镜,一...
    開封第一講書人閱讀 49,950評論 1 291
  • 那天,我揣著相機與錄音润歉,去河邊找鬼模狭。 笑死,一個胖子當著我的面吹牛踩衩,可吹牛的內容都是我干的嚼鹉。 我是一名探鬼主播,決...
    沈念sama閱讀 39,090評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼驱富,長吁一口氣:“原來是場噩夢啊……” “哼锚赤!你這毒婦竟也來了?” 一聲冷哼從身側響起褐鸥,我...
    開封第一講書人閱讀 37,817評論 0 268
  • 序言:老撾萬榮一對情侶失蹤线脚,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后叫榕,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體浑侥,經...
    沈念sama閱讀 44,275評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 36,592評論 2 327
  • 正文 我和宋清朗相戀三年翠霍,在試婚紗的時候發(fā)現(xiàn)自己被綠了锭吨。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,724評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡寒匙,死狀恐怖零如,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情锄弱,我是刑警寧澤考蕾,帶...
    沈念sama閱讀 34,409評論 4 333
  • 正文 年R本政府宣布,位于F島的核電站会宪,受9級特大地震影響肖卧,放射性物質發(fā)生泄漏。R本人自食惡果不足惜掸鹅,卻給世界環(huán)境...
    茶點故事閱讀 40,052評論 3 316
  • 文/蒙蒙 一塞帐、第九天 我趴在偏房一處隱蔽的房頂上張望拦赠。 院中可真熱鬧,春花似錦葵姥、人聲如沸荷鼠。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,815評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽允乐。三九已至,卻和暖如春削咆,著一層夾襖步出監(jiān)牢的瞬間牍疏,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,043評論 1 266
  • 我被黑心中介騙來泰國打工拨齐, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留鳞陨,地道東北人。 一個月前我還...
    沈念sama閱讀 46,503評論 2 361
  • 正文 我出身青樓瞻惋,卻偏偏與公主長得像炊邦,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子熟史,可洞房花燭夜當晚...
    茶點故事閱讀 43,627評論 2 350

推薦閱讀更多精彩內容