Activity啟動(dòng)流程(下)

創(chuàng)建線程從ActivityThread.main開(kāi)始

public static void main(String[] args){
    ...
    Looper.prepareMainLooper(); 
    //初始化Looper
    ...
    ActivityThread thread = new ActivityThread();
    //實(shí)例化一個(gè)ActivityThread
    thread.attach(false);
    //這個(gè)方法最后就是為了發(fā)送出創(chuàng)建Application的消息
    ... 
    Looper.loop();
    //主線程進(jìn)入無(wú)限循環(huán)狀態(tài),等待接收消息
}

然后 attach Application

public void attach(boolean system){
    ...
    final IActivityManager mgr = ActivityManagerNative.getDefault();  
    //獲得IActivityManager實(shí)例,ActivityManager
    try {
        mgr.attachApplication(mAppThread);
    } catch (RemoteException ex) {
        throw ex.rethrowFromSystemServer();
    }
    ...
}
public final void attachApplication(IApplicationThread thread, long startSeq) {
    synchronized (this) {
        int callingPid = Binder.getCallingPid();
        final int callingUid = Binder.getCallingUid();
        final long origId = Binder.clearCallingIdentity();
        attachApplicationLocked(thread, callingPid, callingUid, startSeq);
        Binder.restoreCallingIdentity(origId);
    }
}

public void attachApplicationLocked(IApplicationThread app){
  ...
// Find the application record that is being attached
 thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
                        null, null, null, testMode,
                        mBinderTransactionTrackingEnabled, enableTrackAllocation,
                        isRestrictedBackupMode || !normalMode, app.persistent,
                        new Configuration(getGlobalConfiguration()), app.compat,
                        getCommonServicesLocked(app.isolated),
                        mCoreSettingsObserver.getCoreSettingsLocked(),
                        buildSerial, isAutofillCompatEnabled);
  ...
 // See if the top visible activity is waiting to run in this process...
   if (normalMode) {
        try {
           // 這里會(huì)去 launch activity
            if (mStackSupervisor.attachApplicationLocked(app)) {
                didSomething = true;
            }
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
           badApp = true;
        }
   }
}
 // ApplicationThread
public final void bindApplication(String processName, 
    ApplicationInfo appInfo,
    List<ProviderInfo> providers, 
    ComponentName instrumentationName,
    ProfilerInfo profilerInfo, 
    Bundle instrumentationArgs,
    IInstrumentationWatcher instrumentationWatcher,
    IUiAutomationConnection instrumentationUiConnection, 
    int debugMode,
    boolean enableBinderTracking, 
    boolean trackAllocation,
    boolean isRestrictedBackupMode, 
    boolean persistent, 
    Configuration config,
    CompatibilityInfo compatInfo, 
    Map<String, IBinder> services, 
    Bundle coreSettings){

    ...
    sendMessage(H.BIND_APPLICATION, data);
}

private void handleBindApplication(AppBindData data) {
    ...
    mInstrumentation = (Instrumentation)
        cl.loadClass(data.instrumentationName.getClassName())
        .newInstance();
    //通過(guò)反射初始化一個(gè)Instrumentation
    ...
    Application app = data.info.makeApplication(data.restrictedBackupMode, null);
    //通過(guò)LoadedApp命令創(chuàng)建Application實(shí)例
    mInitialApplication = app;
    ...
    mInstrumentation.callApplicationOnCreate(app);
    //讓儀器調(diào)用Application的onCreate()方法
    ...
}

public Application makeApplication(boolean forceDefaultAppClass,
    Instrumentation instrumentation) {
    ...
    String appClass = mApplicationInfo.className;
    //Application的類名。明顯是要用反射了。
    ...
    ContextImpl appContext = ContextImpl.createAppContext(mActivityThread
        , this);
    //留意下Context
    app = mActivityThread.mInstrumentation
        .newApplication( cl, appClass, appContext);
    //通過(guò)Instrumentation創(chuàng)建Application
    ...
}

static public Application newApplication(Class<?> clazz
    , Context context) throws InstantiationException
    , IllegalAccessException
    , ClassNotFoundException {
        Application app = (Application)clazz.newInstance();
        //反射創(chuàng)建,簡(jiǎn)單粗暴
        app.attach(context);
        //關(guān)注下這里,Application被創(chuàng)建后第一個(gè)調(diào)用的方法。
        //目的是為了綁定Context。
        return app;
    }

Activity啟動(dòng)流程(上) 中,這一段過(guò)程是在40-41之間執(zhí)行的,創(chuàng)建完 ApplicationThread 后,經(jīng)過(guò)層層調(diào)用,生成 LaunchActivityItem 來(lái)發(fā)送 LAUNCH_ACTIVITY 消息

private void handleLaunchActivity(ActivityClientRecord r
 , Intent customIntent
 , String reason) {
 ...
 Activity a = performLaunchActivity(r, customIntent);
 ...
 if (a != null) {
     ...
     handleResumeActivity(r.token
     , false
     , r.isForward
     ,!r.activity.mFinished && !r.startsNotResumed
     , r.lastProcessedSeq, reason);
     //Activity創(chuàng)建成功就往onResume()走了!
     ...
 }
}

private Activity performLaunchActivity(ActivityClientRecord r
 , Intent customIntent) {
 ...
ContextImpl appContext = createBaseContextForActivity(r);
java.lang.ClassLoader cl = appContext.getClassLoader();
 activity = mInstrumentation.newActivity(
      cl, component.getClassName(), r.intent);
 //通過(guò)儀表來(lái)創(chuàng)建Activity
 ...
  Application app = r.packageInfo.makeApplication(false
  , mInstrumentation);
  //前面說(shuō)過(guò),是在獲取Application
 ...
 activity.attach(appContext
     , this
     , getInstrumentation()
     , r.token
     ,.ident
     , app
     , r.intent
     , r.activityInfo
     , title
     , r.parent
     , r.embeddedID
     , r.lastNonConfigurationInstances
     , config
     ,r.referrer
     , r.voiceInteractor
     , window);
 ...
 if (r.isPersistable()) {
     mInstrumentation.callActivityOnCreate(
       activity, r.state, r.persistentState);
 } else {
     mInstrumentation.callActivityOnCreate(activity, r.state);
 }
 //根據(jù)是否可持久化選擇onCreate()方法。
 ...
}

public Activity newActivity(ClassLoader cl, String className,
         Intent intent)
         throws InstantiationException
         , IllegalAccessException,
         ClassNotFoundException {
     return (Activity)cl.loadClass(className).newInstance();
     //反射實(shí)例化Activity而已
 }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容