当前位置:   article > 正文

Android Activity的启动流程源码解析(8.0)

Android Activity的启动流程源码解析(8.0)

一,写在前面

       Activity是Android四大组件之一,用于直接跟用户进行交互,本篇文章将介绍Activity的启动流程。用户启动Activity的方式大致有两种:一种是在桌面点击应用程序的图标,进入应用程序的主界面;另一种是在应用程序中,进入一个新的Activity。前者,桌面其实是系统应用launcher的界面,点击应用程序图标,会进行应用程序的主界面,实质是从一个应用的Activity进入另一个应用Activity。
       因此,不管是从桌面进入应用主界面,还是在应用里进入一个新的Activity,最终都会调用Activity$startActivity方法。
       值得一提的是,Android 5.0,7.0等版本中启动Activity的源码有点小差异,版本的升级只是对代码做了一些封装,最终都会把启动Activity的任务交给ApplicationThread来处理。

二,Activity工作流程的前半部分析

       查看Activity$startActivity源码如下:
    @Override
    public void startActivity(Intent intent) {
        this.startActivity(intent, null);
    }

    //继续查看

    @Override
    public void startActivity(Intent intent, @Nullable Bundle options) {
        if (options != null) {
            startActivityForResult(intent, -1, options);
        } else {
            // Note we want to go through this call for compatibility with
            // applications that may have overridden the method.
            startActivityForResult(intent, -1);
        }
    }
       其实Activity$startActivity有几个其他重载的方法,但是最终都会执行到Activity$startActivityForResult方法。如果是调用startActivity(intent)启动Activity,那么requestCode参数则传入-1,表示当前Activity启动一个新的Activity后,不需要获取新的Activity返回来的数据。关于调用startActivityForResult启动Activity的情况,就不多介绍了,继续下一步。
       
       查看Activity$startActivityForResult源码:
    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
        if (mParent == null) {
            Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);
            if (ar != null) {
                mMainThread.sendActivityResult(
                    mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                    ar.getResultData());
            }
            if (requestCode >= 0) {
                // If this start is requesting a result, we can avoid making
                // the activity visible until the result is received.  Setting
                // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
                // activity hidden during this time, to avoid flickering.
                // This can only be done when a result is requested because
                // that guarantees we will get information back when the
                // activity is finished, no matter what happens to it.
                mStartedActivity = true;
            }

            cancelInputsAndStartExitTransition(options);
            // TODO Consider clearing/flushing other event sources and events for child windows.
        } else {
            if (options != null) {
                mParent.startActivityFromChild(this, intent, requestCode, options);
            } else {
                // Note we want to go through this method for compatibility with
                // existing applications that may have overridden it.
                mParent.startActivityFromChild(this, intent, requestCode);
            }
        }
    }
       第3行,mParent指的是ActivityGroup,可以在一个界面里嵌套多个Activity。随着版本的升级,在API13以后就废弃掉了。
       第5行,调用了方法Instrumentation$execStartActivity,因为mParent为null。
       第6行,mMainThread是一个ActivityThread对象,该对象初始化在当前Activity的attach方法中。
       attach方法是在启动Activity之前被调用,本篇文章后面会给出解释。attach方法主要是注册一些接口,给一些变量初始化值,其中就创建了PhoneWindow的实例,为创建WindowManagerImpl对象做准备。通过WindowManager可以添加,删除,更新窗口,从代码角度来说 ,增加,删除,更新操作的是View。对WindowManager的不了解的,可以查看文章 Android 源码解析之WindowManager添加窗口
       前面提到mMainThread是一个ActivityThread对象,mMainThread.getApplicationThread()返回的是一个ApplicationThread对象,ApplicationThread是ActivityThread的内部类。
       查看ApplicationThread源码如下:
    public final class ActivityThread {
    
	final ApplicationThread mAppThread = new ApplicationThread();

	//...code

	private class ApplicationThread extends IApplicationThread.Stub {
	
		//...code
	}

    }
       ApplicationThread继承了IApplicationThread.Stub,说明这里Android使用了AIDL技术实现进程间通信。当然完全也可以不用AIDL技术,而选择手写AIDL文件自动生成的Java代码,在其他版本上就是这么处理。 IApplicationThread是一个AIDl接口,继承了IInterface接口;Stub是接口IApplicationThread的内部类,继承了Binder类,实现了IApplicationThread接口。因此,ApplicationThread就是一个Binder对象,它重写了IApplicationThread接口的抽象方法,这些重写的方法一定会在某一刻,基于Binder机制被调用。至于,这一刻啥时候发生,在后面就知道啦,这里就此打住~

       回到Activity$startActivityForResult方法,第5行,调用了方法Instrumentation$execStartActivity。
       查看Instrumentation$execStartActivity的源码:
    public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
        IApplicationThread whoThread = (IApplicationThread) contextThread;

        try {
            intent.migrateExtraStreamToClipData();
            intent.prepareToLeaveProcess(who);
            int result = ActivityManager.getService()
                .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;
    }
       第9行,ActivityManager.getService()返回的是什么呢。
       
       查看ActivityManager$getService源码:
    /**
     * @hide
     */
    public static IActivityManager getService() {
        return IActivityManagerSingleton.get();
    }

    //继续查看

    private static final Singleton<IActivityManager> IActivityManagerSingleton =
            new Singleton<IActivityManager>() {
                @Override
                protected IActivityManager create() {
                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                    final IActivityManager am = IActivityManager.Stub.asInterface(b);
                    return am;
                }
            };

	    //...code

    }
        变量IActivityManagerSingleton是一个Singleton对象,查看Singleton源码如下:
public abstract class Singleton<T> {
    private T mInstance;

    protected abstract T create();

    public final T get() {
        synchronized (this) {
            if (mInstance == null) {
                mInstance = create();
            }
            return mInstance;
        }
    }
}
       Singleton是一个抽象类,有一个抽象方法create()。有一个get()方法,内部通过单例模式创建T对象,调用create方法创建T对象,且只会创建一次T对象。
       继续查看create方法的具体实现,IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE)获取一个关联了系统服务ActivityManagerService的Binder对象;IActivityManager.Stub.asInterface(b)返回一个IActivityManager的代理对象,基于Binder机制,通过调用代理对象的方法,使得系统服务ActivityManagerService对应的方法被调用。可以猜测ActivityManagerService肯定继承了IActivityManager.Stub,事实也确实如此。
       ActivityManagerService源码如下:
    public class ActivityManagerService extends IActivityManager.Stub
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
	
	//...code
	
    }

       回到Instrumentation$execStartActivity方法的第9行,ActivityManager.getService().startActivity(...),就是IActivityManager的代理对象调用了startActivity方法,通过Binder机制,它会使系统服务ActivityManagerService的startActivity方法被调用。因此,启动Activity的操作就交给了系统服务ActivityManagerService来处理了。

 

三,启动Activity的操作交给ActivityManagerService处理  

      查看 ActivityManagerService$startActivity源码:
    @Override
    public final int startActivity(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                resultWho, requestCode, startFlags, profilerInfo, bOptions,
                UserHandle.getCallingUserId());
    }

    //继续查看

    @Override
    public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
        enforceNotIsolatedCaller("startActivity");
        userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
                userId, false, ALLOW_FULL_ONLY, "startActivity", null);
        // TODO: Switch to user app stacks here.
        return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
                resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
                profilerInfo, null, null, bOptions, false, userId, null, null,
                "startActivityAsUser");
    }
       
       查看ActivityStarter源码如下:
final int startActivityMayWait(IApplicationThread caller, int callingUid,
            String callingPackage, Intent intent, String resolvedType,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            IBinder resultTo, String resultWho, int requestCode, int startFlags,
            ProfilerInfo profilerInfo, WaitResult outResult,
            Configuration globalConfig, Bundle bOptions, boolean ignoreTargetSecurity, int userId,
            IActivityContainer iContainer, TaskRecord inTask, String reason) {
	    
	    //...code

	    int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType,
                    aInfo, rInfo, voiceSession, voiceInteractor,
                    resultTo, resultWho, requestCode, callingPid,
                    callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                    options, ignoreTargetSecurity, componentSpecified, outRecord, container,
                    inTask, reason);

	    //...code	    
}


	//继续查看

int startActivityLocked(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
            String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
            String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
            ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
            ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,
            TaskRecord inTask, String reason) {
	    
	//...code    

	    mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
                aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
                callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
                container, inTask);
	//...code    
}


       //继续查看

private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
            String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
            String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
            ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
            ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,
            TaskRecord inTask) {

	//...code

	doPendingActivityLaunchesLocked(false);

	//...code
}


     //继续查看
final void doPendingActivityLaunchesLocked(boolean doResume) {
	//...code

                startActivity(pal.r, pal.sourceRecord, null, null, pal.startFlags, resume, null,
                        null, null /*outRecords*/);

	//...code
}    


    //继续查看

private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {
       //...code

            result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, outActivity);
        
       //...code 
} 


    //继续查看

 // Note: This method should only be called from {@link startActivity}.
    private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity) {
	//...code 

	mSupervisor.resumeFocusedStackTopActivityLocked();
	
	//...code 
}
       变量mSupervisor是一个ActivityStackSupervisor对象。
       查看ActivityStackSupervisor源码如下:
boolean resumeFocusedStackTopActivityLocked() {
        return resumeFocusedStackTopActivityLocked(null, null, null);
}

//继续查看

boolean resumeFocusedStackTopActivityLocked(
            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
        //...code

	mFocusedStack.resumeTopActivityUncheckedLocked(null, null);

	//...code
}
       
       mFocusedStack是一个ActivityStack对象;
       ActivityStack源码如下:
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
        if (mStackSupervisor.inResumeTopActivity) {
	//...code

	result = resumeTopActivityInnerLocked(prev, options);

	//...code

}

//继续查看

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
	//...code

	mStackSupervisor.startSpecificActivityLocked(next, true, true);

	//...code

}
       mSupervisor是一个ActivityStackSupervisor对象;
       
       查看ActivityStackSupervisor源码如下:
void startSpecificActivityLocked(ActivityRecord r,
            boolean andResume, boolean checkConfig) {
	    
	//...code

	realStartActivityLocked(r, app, andResume, checkConfig);

	//...code

}

//继续查看

final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
            boolean andResume, boolean checkConfig) throws RemoteException {
	//...code

	app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                    System.identityHashCode(r), r.info,
                    // TODO: Have this take the merged configuration instead of separate global and
                    // override configs.
                    mergedConfiguration.getGlobalConfiguration(),
                    mergedConfiguration.getOverrideConfiguration(), r.compat,
                    r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
                    r.persistentState, results, newIntents, !andResume,
                    mService.isNextTransitionForward(), profilerInfo);

	//...code	    
}
       变量app是一个ProcessRecord对象,它的成员变量thread是IApplicationThread类型,因此app.thread是一个IApplicationThread的代理对象。
       前面介绍ApplicationThread继承了IApplicationThread.Stub,并提出ApplicationThread重写接口IApplicationThread的抽象方法在哪里被调用。有意思的是,app.thread调用scheduleLaunchActivity方法,通过Binder机制,会使ApplicationThread$scheduleLaunchActivity方法被调用。
       于是,基于Binder机制,实现了一次进程间的通信,将启动Activity的操作交给了ApplicationThread类。


四,启动Activity的操作,交给ApplicationThread来处理

       前面有介绍ApplicationThread是ActivityThread的内部类,因此ApplicationThread可以调用外部类ActivityThread的方法,也可以这样理解,启动Activity的操作交给了ActivityThread来处理。好了,下面开始进入主题啦。
       
       查看ApplicationThread$scheduleLaunchActivity方法源码如下:
	@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);
        }
       第11行,创建了一个ActivityClientRecord对象,用于封装启动Activity需要的一些参数值。
       第34行,调用ActivityThread$sendMessage方法,查看其源码如下:
  1. private void sendMessage(int what, Object obj) {
  2. sendMessage(what, obj, 0, 0, false);
  3. }
  4. //继续查看
  5. private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
  6. if (DEBUG_MESSAGES) Slog.v(
  7. TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
  8. + ": " + arg1 + " / " + obj);
  9. Message msg = Message.obtain();
  10. msg.what = what;
  11. msg.obj = obj;
  12. msg.arg1 = arg1;
  13. msg.arg2 = arg2;
  14. if (async) {
  15. msg.setAsynchronous(true);
  16. }
  17. mH.sendMessage(msg);
  18. }
       第19行,mH是一个H对象,类H是ActivityThread的内部类,并继承了Handler。于是,启动Activity的操作放在处理消息的方法H$handleMessage中。
       查看H$handleMessage源码如下:
private class H extends Handler {

    //...code
	public void handleMessage(Message msg) {
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
            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, "LAUNCH_ACTIVITY");
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                } break;
    	
	//...code

}
       第9行,取出Message对象中的obj字段,它是一个ActivityClientRecord对象;
       第10行,调用ActivityThread$getPackageInfoNoCheck方法,返回一个LoadedApk对象,并将该对象封装到ActivityClientRecord的packgeInfo字段中。
       第11行,调用ActivityThread$handleLaunchActivity方法启动Activity;

       查看ActivityThread$handleLaunchActivity源码如下:
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);
		    
        //...

    } else {
        // If there was an error, for any reason, tell the activity manager to stop us.
        try {
             ActivityManager.getService()
                    .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                            Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
    }

}
       第4行,调用performLaunchActivity方法启动Activity;
       第11行,若a不为空,则调用handleResumeActivity方法,内部会调用Activity$onResume方法。具体的代码流程还是比较好跟的,由于不是本篇的重点,有兴趣的哥们可以自己去研究。
       第16行,当a为空,也就是创建Activity的实例出错了,走else语句。ActivityManager.getService()前面已经分析过了,返回IActivityManager的代理对象,调用该代理对象的方法,会向系统服务ActivityManagerService发送请求,基于Binder机制,最终会调用ActivityManagerService$finishActivity方法。
       也就是说,当创建Activity实例出错后,停止启动Activity的具体操作交给ActivityManagerService来处理。

       回到启动Activity的流程,查看ActivityThread$performLaunchActivity源码如下:
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);
        }

        ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        
	    //...code

            java.lang.ClassLoader cl = appContext.getClassLoader();
            if (appContext.getApplicationContext() instanceof Application) {
                activity = ((Application) appContext.getApplicationContext())
                        .instantiateActivity(cl, component.getClassName(), r.intent);
            }
            if (activity == null) {
                activity = mInstrumentation.newActivity(
                        cl, component.getClassName(), r.intent);
            }
            
	    //...code

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

            //...code

            if (activity != null) {
                
		//...code

                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, window, r.configCallback);

                //...code

                mInstrumentation.callActivityOnCreate(activity, r.state);

		//...code
	     }
   
        return activity;
}
       ActivityThread$performLaunchActivity方法的操作:
       1,获取要启动的Activity的ComponentName对象:里面包含了包名,类名相关的信息;
       2,创建Activity的上下文环境:即创建了ContextImpl对象;
       3,创建Activity的实例:调用Instrumentation$newActivity方法,并使用类加载器创建Activity对象;
       4,创建Application对象;
       5,调用Activity$attach方法:初始化Activity类里的一些数据;
       6,启动Activity:调用Instrumentation$callActivityOnCreate方法;

        分析ActivityThread$performLaunchActivity方法:
        步骤2,创建了Activity的上下文环境,ContextImpl是抽象类Context的实现类,有关Context的操作的具体实现,大多数由ContextImpl完成。
       查看ActivityThread$createBaseContextForActivity源码如下:
private ContextImpl createBaseContextForActivity(ActivityClientRecord r) {

	//...code

	ContextImpl appContext = ContextImpl.createActivityContext(
                this, r.packageInfo, r.activityInfo, r.token, displayId, r.overrideConfig);
	
	//...code

	return appContext;
}
       继续查看ContextImpl$createActivityContext源码如下:
static ContextImpl createActivityContext(ActivityThread mainThread,
            LoadedApk packageInfo, ActivityInfo activityInfo, IBinder activityToken, int displayId,
            Configuration overrideConfiguration) {
	    //...code

	    ContextImpl context = new ContextImpl(null, mainThread, packageInfo, activityInfo.splitName,
                activityToken, null, 0, classLoader);
	    
	   //...code 
}
        很显然,最终创建了一个ContextImpl对象。

        步骤3,创建了一个Activity的实例。
        查看Instrumentation$newActivity源码如下:
public Activity newActivity(ClassLoader cl, String className,
            Intent intent)
            throws InstantiationException, IllegalAccessException,
            ClassNotFoundException {
        return (Activity)cl.loadClass(className).newInstance();
    }
       通过ClassLoader创建Activity的实例。

        步骤4,创建了Application对象,具体分析往下看呗~
       查看LoadedApk$makeApplication方法源码如下:
public Application makeApplication(boolean forceDefaultAppClass,
            Instrumentation instrumentation) {
        if (mApplication != null) {
            return mApplication;
        }

	Application app = null;

	//...

	app = mActivityThread.mInstrumentation.newApplication(
                    cl, appClass, appContext);
	
	//...

	mApplication = app;

	instrumentation.callApplicationOnCreate(app);
	//...

	return app;
}
        第3行,当mApplication不为null时,也就是Application对象已经存在时,直接返回mApplication。很显然Application是一个单例对象,一个应用程序中只存在一个Application对象。
       第11行,当应用程序内存中没有Application对象时,创建一个Application对象。跟Activity一样,都是通过类加载器ClassLoader来创建实例。具体代码就不再展示,有兴趣哥们可以去验证。
       第16行,将Application对象app赋给字段mApplication。
       第18行,调用Application的onCreate方法。
       查看Instrumentation$callApplicationOnCreate方法源码:
  1. public void callApplicationOnCreate(Application app) {
  2. app.onCreate();
  3. }
       
        步骤5,调用Activity$attach方法初始化数据。
       查看Activity$attach方法源码:
    final void attach(Context context, ActivityThread aThread,
            Instrumentation instr, IBinder token, int ident,
            Application application, Intent intent, ActivityInfo info,
            CharSequence title, Activity parent, String id,
            NonConfigurationInstances lastNonConfigurationInstances,
            Configuration config, String referrer, IVoiceInteractor voiceInteractor,
            Window window) {
        attachBaseContext(context);

        mFragments.attachHost(null /*parent*/);

        mWindow = new PhoneWindow(this, window);
        mWindow.setWindowControllerCallback(this);
        mWindow.setCallback(this);
        mWindow.setOnWindowDismissedCallback(this);
        mWindow.getLayoutInflater().setPrivateFactory(this);
        if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
            mWindow.setSoftInputMode(info.softInputMode);
        }
        if (info.uiOptions != 0) {
            mWindow.setUiOptions(info.uiOptions);
        }
        mUiThread = Thread.currentThread();

        mMainThread = aThread;
        mInstrumentation = instr;
        mToken = token;
        mIdent = ident;
        mApplication = application;
        mIntent = intent;
        mReferrer = referrer;
        mComponent = intent.getComponent();
        mActivityInfo = info;
        mTitle = title;
        mParent = parent;
        mEmbeddedID = id;
        mLastNonConfigurationInstances = lastNonConfigurationInstances;
        if (voiceInteractor != null) {
            if (lastNonConfigurationInstances != null) {
                mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
            } else {
                mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
                        Looper.myLooper());
            }
        }

        mWindow.setWindowManager(
                (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
                mToken, mComponent.flattenToString(),
                (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
        if (mParent != null) {
            mWindow.setContainer(mParent.getWindow());
        }
        mWindowManager = mWindow.getWindowManager();
        mCurrentConfig = config;
    }
       第8行,参数context:步骤2中创建的ContextImpl对象传入的。attachBaseContext方法:给ContextWrapper的成员变量mBase设置值为ContextImpl对象。ContextWrapper是Context的一个子类,具体的代码流程感兴趣的哥们可以去验证~
       第12行,创建了窗口对象PhoneWindow;
       第13~15行,给窗口对象注册监听接口;
       第23~37行,初始化一些变量的值;
       第47行,通过窗口Window创建WindowManagerImpl的实例;
       第54行,将47行创建的WindowManagerImpl的实例,设置给变量mWindowManager;
       有关WindowManager操作View的具体分析,见文章 Android 源码解析之WindowManager添加窗口 ;

        步骤6,调用Instrumentation$callActivityOnCreate方法启动Activity。
       查看Instrumentation$callActivityOnCreate源码:
public void callActivityOnCreate(Activity activity, Bundle icicle) {
        prePerformCreate(activity);
        activity.performCreate(icicle);
        postPerformCreate(activity);
}
       第3行,调用了Activity$performCreate方法。
       查看Activity$performCreate源码如下:
final void performCreate(Bundle icicle) {
        restoreHasCurrentPermissionRequest(icicle);
        onCreate(icicle);
        mActivityTransitionState.readState(icicle);
        performCreateCommon();
}
       第3行,调用了Activity的onCreate方法启动Activity,终于找到期待已久的onCreate方法啦~

      

       到这里,Activity的启动流程就分析完毕了^_^

                    













       






       





       




       





声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/784560
推荐阅读
相关标签
  

闽ICP备14008679号