文章目录

  • 点击桌面应用程序创建application和activity流程
  • 点击 startActivity() 时的调用流程
  • 问题: 为什么启动时会先调用栈顶activity的onPause()
  • 问题:为什么requestWindowFeature(Window.FEATURE_NO_TITLE);要在setContentView()之前.

点击桌面应用程序创建application和activity流程

  • 首先从APP程序入口启动 main 函数开始。看下 ActivityThread 的 main 方法
    main方法中做了一些 Loop 的初始化,Application绑定流程的调用等,具体看代码:代码中有备注,省略了部分代码
    public static void main(String[] args) {// ... 省略上面代码// 内部是初始化 main Looper 逻辑 涉及到 Handler 的初始化知识Looper.prepareMainLooper();// ... 省略上面代码// 创建 ActivityThread 对象ActivityThread thread = new ActivityThread();// 调用 ActivityThread 的 attach 方法// attach 方法内部 创建 Instrumentation 对象,绑定 application ,创建 applicationContext 对象,回调 application 的 onCreate 方法// 下面会介绍一下 attach 的源码thread.attach(false, startSeq);if (sMainThreadHandler == null) {sMainThreadHandler = thread.getHandler();}if (false) {Looper.myLooper().setMessageLogging(newLogPrinter(Log.DEBUG, "ActivityThread"));}// End of event ActivityThreadMain.Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);// 调用 Looper.loop()  内部开启了 for(;;) 去不断接受 Handler 发送的消息Looper.loop();throw new RuntimeException("Main thread loop unexpectedly exited");}
  • activityThread 的 attach 方法
    创建 Instrumentation 对象,绑定 application ,创建 applicationContext 对象,回调 application 的 onCreate 方法
    private void attach(boolean system, long startSeq) {// ... 代码省略if (!system) { // 默认传入的是 false// 通过 Binder机制 ActivityManager.getService(); 获取 ActivityManagerServicefinal IActivityManager mgr = ActivityManager.getService();try {// 绑定 attachApplication 下一部分会介绍具体绑定流程mgr.attachApplication(mAppThread, startSeq);} catch (RemoteException ex) {throw ex.rethrowFromSystemServer();}// ...} else {// ...}// 代码省略...ViewRootImpl.addConfigCallback(configChangedCallback);}
  • 上面 attach 中 mgr.attachApplication(mAppThread, startSeq); 方法是怎么绑定 application 的。进入 ActivityManagerService 的 attachApplication
    @Overridepublic final void attachApplication(IApplicationThread thread, long startSeq) {synchronized (this) {// 通过 Binder 获取 PID ,PID和UID都是进程创建应用的时候系统指定的int callingPid = Binder.getCallingPid();// 获取 UIDfinal int callingUid = Binder.getCallingUid();final long origId = Binder.clearCallingIdentity();// 最终调用到了 attachApplicationLockedattachApplicationLocked(thread, callingPid, callingUid, startSeq);Binder.restoreCallingIdentity(origId);}}
  • ActivityManagerService 的 attachApplicationLocked(thread, callingPid, callingUid, startSeq);
    这里只挑一些主要代码去贴出来
    @GuardedBy("this")private final boolean attachApplicationLocked(IApplicationThread thread,int pid, int callingUid, long startSeq) {// ProcessRecord AMS通过ProcessRecord来维护进程运行时的信息ProcessRecord app;long startTime = SystemClock.uptimeMillis();// 判断 pid 和 uid 是否存在则创建 ProcessRecordif (pid != MY_PID && pid >= 0) {synchronized (mPidsSelfLocked) {app = mPidsSelfLocked.get(pid);}} else {app = null;}// ... 代码省略一大堆// 在下面就是调用  thread.bindApplication  这里的 thread 是 IapplicationThreadif (app.isolatedEntryPoint != null) {// This is an isolated process which should just call an entry point instead of// being bound to an application.thread.runIsolatedEntryPoint(app.isolatedEntryPoint, app.isolatedEntryPointArgs);} else if (app.instr != null) {// bindApplication 传入了各种app相关的信息 下面看 bindApplication 是怎么绑定的thread.bindApplication(processName, appInfo, providers,app.instr.mClass,profilerInfo, app.instr.mArguments,app.instr.mWatcher,app.instr.mUiAutomationConnection, testMode,mBinderTransactionTrackingEnabled, enableTrackAllocation,isRestrictedBackupMode || !normalMode, app.persistent,new Configuration(getGlobalConfiguration()), app.compat,getCommonServicesLocked(app.isolated),mCoreSettingsObserver.getCoreSettingsLocked(),buildSerial, isAutofillCompatEnabled);} else {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);}// ... 代码省略// 做检测 查看顶部可见活动是否等待此进程中进行if (normalMode) {try {// 后面会介绍 里面会具体解锁 activity 的创建运行if (mStackSupervisor.attachApplicationLocked(app)) {didSomething = true;}} catch (Exception e) {Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);badApp = true;}}// ... 下面代码省略}
  • thread.bindApplication 方法。IApplicationThread 中
    经过一系列的操作 最后把各种信息保存在了 AppBindData 中,它就是javabean,最后调用了
    sendMessage(H.BIND_APPLICATION, data);
        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 services, Bundle coreSettings,String buildSerial, boolean autofillCompatibilityEnabled) {if (services != null) {if (false) {// Test code to make sure the app could see the passed-in services.for (Object oname : services.keySet()) {if (services.get(oname) == null) {continue; // AM just passed in a null service.}String name = (String) oname;// See b/79378449 about the following exemption.switch (name) {case "package":case Context.WINDOW_SERVICE:continue;}if (ServiceManager.getService(name) == null) {Log.wtf(TAG, "Service " + name + " should be accessible by this app");}}}// Setup the service cache in the ServiceManagerServiceManager.initServiceCache(services);}setCoreSettings(coreSettings);// 将各种数据保存下载AppBindData data = new AppBindData();data.processName = processName;data.appInfo = appInfo;data.providers = providers;data.instrumentationName = instrumentationName;data.instrumentationArgs = instrumentationArgs;data.instrumentationWatcher = instrumentationWatcher;data.instrumentationUiAutomationConnection = instrumentationUiConnection;data.debugMode = debugMode;data.enableBinderTracking = enableBinderTracking;data.trackAllocation = trackAllocation;data.restrictedBackupMode = isRestrictedBackupMode;data.persistent = persistent;data.config = config;data.compatInfo = compatInfo;data.initProfilerInfo = profilerInfo;data.buildSerial = buildSerial;data.autofillCompatibilityEnabled = autofillCompatibilityEnabled;// 发送handler消息sendMessage(H.BIND_APPLICATION, data);}
  • 接下来看看 Handler 接收 H.BIND_APPLICATION 消息是怎么处理的。
        public void handleMessage(Message msg) {if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));switch (msg.what) {case BIND_APPLICATION:Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");AppBindData data = (AppBindData)msg.obj;handleBindApplication(data);Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);break;
  • ActivityThread 中的 handleBindApplication(data);
    private void handleBindApplication(AppBindData data) {// ... 只贴出主要代码try {// If the app is being launched for full backup or restore, bring it up in// 创建 applicationapp = data.info.makeApplication(data.restrictedBackupMode, null);// Propagate autofill compat stateapp.setAutofillCompatibilityEnabled(data.autofillCompatibilityEnabled);mInitialApplication = app;// don't bring up providers in restricted mode; they may depend on the// app's custom Application classif (!data.restrictedBackupMode) {if (!ArrayUtils.isEmpty(data.providers)) {installContentProviders(app, data.providers);// For process that contains content providers, we want to// ensure that the JIT is enabled "at some point".mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);}}// Do this after providers, since instrumentation tests generally start their// test thread at this point, and we don't want that racing.try {mInstrumentation.onCreate(data.instrumentationArgs);}catch (Exception e) {throw new RuntimeException("Exception thrown in onCreate() of "+ data.instrumentationName + ": " + e.toString(), e);}try {// 调用 appilcation 的 onCreate方法mInstrumentation.callApplicationOnCreate(app);} catch (Exception e) {if (!mInstrumentation.onException(app, e)) {throw new RuntimeException("Unable to create application " + app.getClass().getName()+ ": " + e.toString(), e);}}} finally {// If the app targets < O-MR1, or doesn't change the thread policy// during startup, clobber the policy to maintain behavior of b/36951662if (data.appInfo.targetSdkVersion < Build.VERSION_CODES.O_MR1|| StrictMode.getThreadPolicy().equals(writesAllowedPolicy)) {StrictMode.setThreadPolicy(savedPolicy);}}}
  • 上面代码中 app = data.info.makeApplication(data.restrictedBackupMode, null);
    LoadedApk 中的 makeApplication
    public Application makeApplication(boolean forceDefaultAppClass,Instrumentation instrumentation) {if (mApplication != null) {return mApplication;}Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "makeApplication");Application app = null;// 获取 application的 calssName 这里面是获取的自定义 application 的名字 如果没有则引用系统默认的String appClass = mApplicationInfo.className;if (forceDefaultAppClass || (appClass == null)) {appClass = "android.app.Application";}try {// 通过 calssLoader 来创建 applicationjava.lang.ClassLoader cl = getClassLoader();if (!mPackageName.equals("android")) {Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,"initializeJavaContextClassLoader");initializeJavaContextClassLoader();Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);}// 创建 applicationContexxtContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);app = mActivityThread.mInstrumentation.newApplication(cl, appClass, appContext);appContext.setOuterContext(app);} catch (Exception e) {if (!mActivityThread.mInstrumentation.onException(app, e)) {Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);throw new RuntimeException("Unable to instantiate application " + appClass+ ": " + e.toString(), e);}}mActivityThread.mAllApplications.add(app);mApplication = app;if (instrumentation != null) {try {// 调用 onCreateinstrumentation.callApplicationOnCreate(app);} catch (Exception e) {if (!instrumentation.onException(app, e)) {Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);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().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);}Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);return app;}
  • 这样 application 就创建完成了 ,然后继续回到 ActivityManagerService 中的 attachApplicationLocked 创建完成application之后继续执行后面的代码,有这么一句话
mStackSupervisor.attachApplicationLocked(app)
  • 来具体看看里面是做什么的
    ActivityStackSupervisor 的 attachApplicationLocked
    boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {// 获取进程名final String processName = app.processName;boolean didSomething = false;for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);for (int stackNdx = display.getChildCount() - 1; stackNdx >= 0; --stackNdx) {final ActivityStack stack = display.getChildAt(stackNdx);if (!isFocusedStack(stack)) {continue;}stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);final ActivityRecord top = stack.topRunningActivityLocked();final int size = mTmpActivityList.size();for (int i = 0; i < size; i++) {final ActivityRecord activity = mTmpActivityList.get(i);if (activity.app == null && app.uid == activity.info.applicationInfo.uid&& processName.equals(activity.processName)) {try {// 下面会看一下 realStartActivityLocked 里面是什么逻辑if (realStartActivityLocked(activity, app,top == activity /* andResume */, true /* checkConfig */)) {didSomething = true;}} catch (RemoteException e) {Slog.w(TAG, "Exception in new application when starting activity "+ top.intent.getComponent().flattenToShortString(), e);throw e;}}}}}if (!didSomething) {ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);}return didSomething;}
  • ActivityStackSupervisor 的 realStartActivityLocked
    final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,boolean andResume, boolean checkConfig) throws RemoteException {// ...// Create activity launch transaction.final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,r.appToken);// LaunchActivityItem 就是 manifest里面的 launch回调clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),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, mService.isNextTransitionForward(),profilerInfo));}// Set desired final state.final ActivityLifecycleItem lifecycleItem;if (andResume) {lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());} else {lifecycleItem = PauseActivityItem.obtain();}clientTransaction.setLifecycleStateRequest(lifecycleItem);// Schedule transaction.// 调用 scheduleTransaction 代码在下面会贴出来 mService 就是 AMSmService.getLifecycleManager().scheduleTransaction(clientTransaction);
  • mService.getLifecycleManager().scheduleTransaction(clientTransaction); 方法
    void scheduleTransaction(ClientTransaction transaction) throws RemoteException {final IApplicationThread client = transaction.getClient();transaction.schedule();if (!(client instanceof Binder)) {// If client is not an instance of Binder - it's a remote call and at this point it is// safe to recycle the object. All objects used for local calls will be recycled after// the transaction is executed on client in ActivityThread.transaction.recycle();}}
  • 调用了ClientTransaction 中的 transaction.schedule();
    public void schedule() throws RemoteException {// 调用了 IApplicationThread 的 scheduleTransactionmClient.scheduleTransaction(this);}
  • mClient.scheduleTransaction(this); 调用到了 ActivityThread 中的
@Overridepublic void scheduleTransaction(ClientTransaction transaction) throws RemoteException {ActivityThread.this.scheduleTransaction(transaction);}
  • ActivityThread.this.scheduleTransaction(transaction); 如下:
   /** Prepare and schedule transaction for execution. */void scheduleTransaction(ClientTransaction transaction) {transaction.preExecute(this);// 发送 HandlersendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);}
  • 看一下 Handler 的 EXECUTE_TRANSACTION
                case EXECUTE_TRANSACTION:final ClientTransaction transaction = (ClientTransaction) msg.obj;mTransactionExecutor.execute(transaction);if (isSystem()) {// Client transactions inside system process are recycled on the client side// instead of ClientLifecycleManager to avoid being cleared before this// message is handled.transaction.recycle();}// TODO(lifecycler): Recycle locally scheduled transactions.break;
  • 上面 Handler 中 mTransactionExecutor.execute(transaction); 跳转到 TransactionExecutor 中
    public void execute(ClientTransaction transaction) {final IBinder token = transaction.getActivityToken();log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);// 调用这个方法executeCallbacks(transaction);  executeLifecycleState(transaction);mPendingActions.clear();log("End resolving transaction");}
  • executeCallbacks(transaction); 方法
    public void executeCallbacks(ClientTransaction transaction) {final List<ClientTransactionItem> callbacks = transaction.getCallbacks();if (callbacks == null) {// No callbacks to execute, return early.return;}log("Resolving callbacks");final IBinder token = transaction.getActivityToken();ActivityClientRecord r = mTransactionHandler.getActivityClient(token);// In case when post-execution state of the last callback matches the final state requested// for the activity in this transaction, we won't do the last transition here and do it when// moving to final state instead (because it may contain additional parameters from server).final ActivityLifecycleItem finalStateRequest = transaction.getLifecycleStateRequest();final int finalState = finalStateRequest != null ? finalStateRequest.getTargetState(): UNDEFINED;// Index of the last callback that requests some post-execution state.final int lastCallbackRequestingState = lastCallbackRequestingState(transaction);final int size = callbacks.size();for (int i = 0; i < size; ++i) {final ClientTransactionItem item = callbacks.get(i);log("Resolving callback: " + item);final int postExecutionState = item.getPostExecutionState();final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,item.getPostExecutionState());if (closestPreExecutionState != UNDEFINED) {cycleToPath(r, closestPreExecutionState);}// 执行了 item.execute 就是  LaunchActivityItem 的 executeitem.execute(mTransactionHandler, token, mPendingActions);item.postExecute(mTransactionHandler, token, mPendingActions);if (r == null) {// Launch activity request will create an activity record.r = mTransactionHandler.getActivityClient(token);}if (postExecutionState != UNDEFINED && r != null) {// Skip the very last transition and perform it by explicit state request instead.final boolean shouldExcludeLastTransition =i == lastCallbackRequestingState && finalState == postExecutionState;cycleToPath(r, postExecutionState, shouldExcludeLastTransition);}}}
  • 上面的 item.execute 就是 LaunchActivityItem 的 execute
   @Overridepublic void execute(ClientTransactionHandler client, IBinder token,PendingTransactionActions pendingActions) {Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,mPendingResults, mPendingNewIntents, mIsForward,mProfilerInfo, client);//  调用了 handleLaunchActivity  这句话又回到了 ActivityThread中的 handleLaunchActivityclient.handleLaunchActivity(r, pendingActions, null /* customIntent */);Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);}
    @Overridepublic Activity handleLaunchActivity(ActivityClientRecord r,PendingTransactionActions pendingActions, Intent customIntent) {//  ...// 得到 activity 对象final Activity a = performLaunchActivity(r, customIntent);if (a != null) {r.createdConfig = new Configuration(mConfiguration);reportSizeConfigurations(r);if (!r.activity.mFinished && pendingActions != null) {pendingActions.setOldState(r.state);pendingActions.setRestoreInstanceState(true);pendingActions.setCallOnPostCreate(true);}} 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();}}return a;}
  • performLaunchActivity(r, customIntent);
/**  Core implementation of activity launch. */private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {// 通过 ClassLoader 创建 newActivityContextImpl appContext = createBaseContextForActivity(r);Activity activity = null;try {java.lang.ClassLoader cl = appContext.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);}}//     ...// ...Window window = null;if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {window = r.mPendingRemoveWindow;r.mPendingRemoveWindow = null;r.mPendingRemoveWindowManager = null;}appContext.setOuterContext(activity);// 调用 activity 的attach 方法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);if (customIntent != null) {activity.mIntent = customIntent;}r.lastNonConfigurationInstances = null;checkAndBlockForNetworkAccess();activity.mStartedActivity = false;int theme = r.activityInfo.getThemeResource();if (theme != 0) {activity.setTheme(theme);}activity.mCalled = false;// 这里面调用了  mInstrumentation.callActivityOnCreateif (r.isPersistable()) {mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);} else {mInstrumentation.callActivityOnCreate(activity, r.state);}// ...// ...r.setState(ON_CREATE);// ...// ...}
  • mInstrumentation.callActivityOnCreate
    public void callActivityOnCreate(Activity activity, Bundle icicle) {//     调用了 activity.performCreateprePerformCreate(activity);activity.performCreate(icicle);postPerformCreate(activity);}
  • 在 performLaunchActivity 中调用了 callActivityOnCreate 后,调用了 r.setState(ON_CREATE); 方法 记录了当前是 onCreate状态(实际上保存的就是int值 1-7)
    然后前面在 TransactionExecuor调用了 executeCallbacks(transaction); 之后会继续调用
    executeLifecycleState(transaction);

  • executeLifecycleState

private void executeLifecycleState(ClientTransaction transaction) {// ...// Cycle to the state right before the final requested state.// 这里会继续根据state调用其他的生命周期cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);// Execute the final transition with proper parameters.lifecycleItem.execute(mTransactionHandler, token, mPendingActions);lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);}
  • cycleToPath 然后调用 performLifecycleSequence()
    private void cycleToPath(ActivityClientRecord r, int finish,boolean excludeLastState) {final int start = r.getLifecycleState();log("Cycle from: " + start + " to: " + finish + " excludeLastState:" + excludeLastState);final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);performLifecycleSequence(r, path);}/** Transition the client through previously initialized state sequence. */private void performLifecycleSequence(ActivityClientRecord r, IntArray path) {final int size = path.size();for (int i = 0, state; i < size; i++) {state = path.get(i);log("Transitioning to state: " + state);switch (state) {case ON_CREATE:mTransactionHandler.handleLaunchActivity(r, mPendingActions,null /* customIntent */);break;case ON_START:mTransactionHandler.handleStartActivity(r, mPendingActions);break;case ON_RESUME:mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,r.isForward, "LIFECYCLER_RESUME_ACTIVITY");break;case ON_PAUSE:mTransactionHandler.handlePauseActivity(r.token, false /* finished */,false /* userLeaving */, 0 /* configChanges */, mPendingActions,"LIFECYCLER_PAUSE_ACTIVITY");break;case ON_STOP:mTransactionHandler.handleStopActivity(r.token, false /* show */,0 /* configChanges */, mPendingActions, false /* finalStateRequest */,"LIFECYCLER_STOP_ACTIVITY");break;case ON_DESTROY:mTransactionHandler.handleDestroyActivity(r.token, false /* finishing */,0 /* configChanges */, false /* getNonConfigInstance */,"performLifecycleSequence. cycling to:" + path.get(size - 1));break;case ON_RESTART:mTransactionHandler.performRestartActivity(r.token, false /* start */);break;default:throw new IllegalArgumentException("Unexpected lifecycle state: " + state);}}}

其中的mTransactionHandler 就是 ThreadHandler ,又回到了ThreadHandler中继续下面的生命周期调用。

点击 startActivity() 时的调用流程

  • 调用 startActivity(new Intent()); 方法。
    随着调用会调用到 startActivityForResult
    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,@Nullable Bundle options) {// 重点代码 调用了 Instrumentation 的 execStartActivitymInstrumentation.execStartActivity(this, mMainThread.getApplicationThread(), mToken, this,intent, requestCode, options);}
  • Instrumentation 的 execStartActivity
    public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, String resultWho,Intent intent, int requestCode, Bundle options, UserHandle user) {// 重要代码    调用了 AMS 的   startActivityAsUser 方法int result = ActivityManager.getService().startActivityAsUser(whoThread, who.getBasePackageName(), intent,intent.resolveTypeIfNeeded(who.getContentResolver()),token, resultWho,requestCode, 0, null, options, user.getIdentifier());}
  • AMS 的 startActivityAsUser 方法
    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,boolean validateIncomingUser) {enforceNotIsolatedCaller("startActivity");userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");// 这里面保存了一些信息 比如熟悉的 requestCode userId 等等// 执行的 execute 是调用到了 ActivityStarter 的 execute() 方法return mActivityStartController.obtainStarter(intent, "startActivityAsUser").setCaller(caller).setCallingPackage(callingPackage).setResolvedType(resolvedType).setResultTo(resultTo).setResultWho(resultWho).setRequestCode(requestCode).setStartFlags(startFlags).setProfilerInfo(profilerInfo).setActivityOptions(bOptions).setMayWait(userId).execute();}
  • ActivityStarter 的 execute() 方法
    int execute() {try {// TODO(b/64750076): Look into passing request directly to these methods to allow// 上面传进来的默认是 true  所以后面调用的是 startActivityMayWaitif (mRequest.mayWait) {return startActivityMayWait(mRequest.caller, mRequest.callingUid,mRequest.callingPackage, mRequest.intent, mRequest.resolvedType,mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,mRequest.inTask, mRequest.reason,mRequest.allowPendingRemoteAnimationRegistryLookup);} else {return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,mRequest.ignoreTargetSecurity, mRequest.componentSpecified,mRequest.outActivity, mRequest.inTask, mRequest.reason,mRequest.allowPendingRemoteAnimationRegistryLookup);}} finally {onExecutionComplete();}}
  • ActivityStarter 的 startActivityMayWait() 方法
    private 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, SafeActivityOptions options, boolean ignoreTargetSecurity,int userId, TaskRecord inTask, String reason,boolean allowPendingRemoteAnimationRegistryLookup) {// ... 重要代码int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,allowPendingRemoteAnimationRegistryLookup);}
  • ActivityStarter 的 startActivity() 方法
    private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,// ....//     调用了重载的 startActivitymLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,inTask, allowPendingRemoteAnimationRegistryLookup);if (outActivity != null) {// mLastStartActivityRecord[0] is set in the call to startActivity above.outActivity[0] = mLastStartActivityRecord[0];}return getExternalResult(mLastStartActivityResult);}
  • ActivityStarter 的 startActivity() 方法
    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,SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,ActivityRecord[] outActivity, TaskRecord inTask, String reason,boolean allowPendingRemoteAnimationRegistryLookup) {// ...// ...// 再一次调用了重载的方法return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,true /* doResume */, checkedOptions, inTask, outActivity);}
  • ActivityStarter 的 startActivity() 方法
    private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,ActivityRecord[] outActivity) {int result = START_CANCELED;try {mService.mWindowManager.deferSurfaceLayout();// 调用了 startActivityUnchecked 方法result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,startFlags, doResume, options, inTask, outActivity);} finally {// ...mService.mWindowManager.continueSurfaceLayout();}postStartActivityProcessing(r, result, mTargetStack);return result;}
  • startActivityUnchecked() 方法
    private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,ActivityRecord[] outActivity) {// ...// 调用到了 ActivityStackSupervisor 中的 resumeFocusedStackTopActivityLockedmSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,mOptions);mOptions);// ...}
  • ActivityStackSupervisor 中的 resumeFocusedStackTopActivityLocked
    boolean resumeFocusedStackTopActivityLocked(ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {if (!readyToResume()) {return false;}if (targetStack != null && isFocusedStack(targetStack)) {return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);}final ActivityRecord r = mFocusedStack.topRunningActivityLocked();if (r == null || !r.isState(RESUMED)) {mFocusedStack.resumeTopActivityUncheckedLocked(null, null);} else if (r.isState(RESUMED)) {// Kick off any lingering app transitions form the MoveTaskToFront operation.mFocusedStack.executeAppTransition(targetOptions);}return false;}
  • mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
    boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {if (mStackSupervisor.inResumeTopActivity) {// Don't even start recursing.return false;}boolean result = false;try {// Protect against recursion.mStackSupervisor.inResumeTopActivity = true;// 调用 resumeTopActivityInnerLockedresult = resumeTopActivityInnerLocked(prev, options);final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);if (next == null || !next.canTurnScreenOn()) {checkReadyForSleep();}} finally {mStackSupervisor.inResumeTopActivity = false;}return result;}

经过一些列的调用会走到 ActivityStachSupervisor 中下面的方法

  • startSpecificActivityLocked
    void startSpecificActivityLocked(ActivityRecord r,boolean andResume, boolean checkConfig) {// Is this activity's application already running?ProcessRecord app = mService.getProcessRecordLocked(r.processName,r.info.applicationInfo.uid, true);getLaunchTimeTracker().setLaunchTime(r);// 先判断进程 是否存在 如果进程存在则调用 realStartActivityLockedif (app != null && app.thread != null) {try {realStartActivityLocked(r, app, andResume, checkConfig);return;}}// 如果进程不存在则通过 AMS 去开启进程创建流程mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,"activity", r.intent.getComponent(), false, false, true);}
  • realStartActivityLocked()
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,boolean andResume, boolean checkConfig) throws RemoteException {mService.getLifecycleManager().scheduleTransaction(clientTransaction);}
    void scheduleTransaction(ClientTransaction transaction) throws RemoteException {final IApplicationThread client = transaction.getClient();transaction.schedule();if (!(client instanceof Binder)) {// If client is not an instance of Binder - it's a remote call and at this point it is// safe to recycle the object. All objects used for local calls will be recycled after// the transaction is executed on client in ActivityThread.transaction.recycle();}}

ClientTransaction 的 schedule();

     private IApplicationThread mClient;public void schedule() throws RemoteException {// 这里实际上调用到了当前客户端的 ApplicationThread 的 scheduleTransaction()mClient.scheduleTransaction(this);}
  • scheduleTransaction()
        @Overridepublic void scheduleTransaction(ClientTransaction transaction) throws RemoteException {ActivityThread.this.scheduleTransaction(transaction);}

ActivityThread.this 中 ActivityThread 并没有重写 scheduleTransaction 所以调用的是其父类的ClientTransactionHandler 的 scheduleTransaction() 方法

    void scheduleTransaction(ClientTransaction transaction) {transaction.preExecute(this);sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);}

发送了 EXECUTE_TRANSACTION 消息,接收消息在 ActivityThread 中的 handleMessage()

 public void handleMessage(Message msg) {switch (msg.what) {case EXECUTE_TRANSACTION:final ClientTransaction transaction = (ClientTransaction) msg.obj;mTransactionExecutor.execute(transaction);if (isSystem()) {// Client transactions inside system process are recycled on the client side// instead of ClientLifecycleManager to avoid being cleared before this// message is handled.transaction.recycle();}// TODO(lifecycler): Recycle locally scheduled transactions.break;}
}

// 执行了 LaunchActivityItem 的 execute LaunchActivityItemClientTransactionItem

public void execute(ClientTransaction transaction) {
// 其内部调用了 executeCallbacks
// 该方法内执行了 LaunchActivityItem 的 execute
executeCallbacks(transaction);
}

    @Overridepublic void execute(ClientTransactionHandler client, IBinder token,PendingTransactionActions pendingActions) {Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,mPendingResults, mPendingNewIntents, mIsForward,mProfilerInfo, client);// client 是 ClientTransactionHandler 它的实现类是 ActivityThreadclient.handleLaunchActivity(r, pendingActions, null /* customIntent */);Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);}

所以接下来就到了 ActivityThread 中的 handleLaunchActivity 流程,启动Activity 执行生命周期

问题: 为什么启动时会先调用栈顶activity的onPause()

  • resumeTopActivityInnerLocked
    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {// startPausingLocked 先让栈顶的activity去onPause 然后在去启动新的activity// 所以当启动一个新的activity的时候会先让顶部activity onPause 虽然可见但是已经失去焦点// 内部 pause 原理也是通过发送 Handler 然后出发 state 的改变回调if (mResumedActivity != null) {if (DEBUG_STATES) Slog.d(TAG_STATES,"resumeTopActivityLocked: Pausing " + mResumedActivity);pausing |= startPausingLocked(userLeaving, false, next, false);}// ...// 最后调用了 startSpecificActivityLocked 去启动 activitymStackSupervisor.startSpecificActivityLocked(next, true, false);}
  • startSpecificActivityLocked()
    void startSpecificActivityLocked(ActivityRecord r,boolean andResume, boolean checkConfig) {// Is this activity's application already running?ProcessRecord app = mService.getProcessRecordLocked(r.processName,r.info.applicationInfo.uid, true);getLaunchTimeTracker().setLaunchTime(r);if (app != null && app.thread != null) {try {if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0|| !"android".equals(r.info.packageName)) {// Don't add this if it is a platform component that is marked// to run in multiple processes, because this is actually// part of the framework so doesn't make sense to track as a// separate apk in the process.app.addPackage(r.info.packageName, r.info.applicationInfo.longVersionCode,mService.mProcessStats);}// real startrealStartActivityLocked(r, app, andResume, checkConfig);return;} catch (RemoteException e) {Slog.w(TAG, "Exception when starting activity "+ r.intent.getComponent().flattenToShortString(), e);}// If a dead object exception was thrown -- fall through to// restart the application.}mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,"activity", r.intent.getComponent(), false, false, true);}
  • realStartActivityLocked
   final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,boolean andResume, boolean checkConfig) throws RemoteException {// ...clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),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, mService.isNextTransitionForward(),profilerInfo));// Set desired final state.final ActivityLifecycleItem lifecycleItem;if (andResume) {lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());} else {lifecycleItem = PauseActivityItem.obtain();}// 设置生命周期的状态clientTransaction.setLifecycleStateRequest(lifecycleItem);// 执行生命周期的调用mService.getLifecycleManager().scheduleTransaction(clientTransaction);// ...}
  • mService.getLifecycleManager().scheduleTransaction(clientTransaction);
    下面的代码就和最开始 app启动的activity启动差不多了
    void scheduleTransaction(ClientTransaction transaction) throws RemoteException {final IApplicationThread client = transaction.getClient();transaction.schedule();if (!(client instanceof Binder)) {// If client is not an instance of Binder - it's a remote call and at this point it is// safe to recycle the object. All objects used for local calls will be recycled after// the transaction is executed on client in ActivityThread.transaction.recycle();}}
  • 会调用到 scheduleTransaction
    void scheduleTransaction(ClientTransaction transaction) {transaction.preExecute(this);sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);}
  • 对应 handler 中
case EXECUTE_TRANSACTION:final ClientTransaction transaction = (ClientTransaction) msg.obj;mTransactionExecutor.execute(transaction);if (isSystem()) {// Client transactions inside system process are recycled on the client side// instead of ClientLifecycleManager to avoid being cleared before this// message is handled.transaction.recycle();}
  • TransactionExecutor 中的 execute 方法。
    public void execute(ClientTransaction transaction) {final IBinder token = transaction.getActivityToken();// 指定  callbacksexecuteCallbacks(transaction);executeLifecycleState(transaction);mPendingActions.clear();log("End resolving transaction");}
  • 然后执行executeCallbacks 中的 item.execute(mTransactionHandler, token, mPendingActions);
    public void executeCallbacks(ClientTransaction transaction) {// ...// 执行了 LaunchActivityItem 的 execute                LaunchActivityItemClientTransactionItemitem.execute(mTransactionHandler, token, mPendingActions);item.postExecute(mTransactionHandler, token, mPendingActions);if (r == null) {// Launch activity request will create an activity record.r = mTransactionHandler.getActivityClient(token);}if (postExecutionState != UNDEFINED && r != null) {// Skip the very last transition and perform it by explicit state request instead.final boolean shouldExcludeLastTransition =i == lastCallbackRequestingState && finalState == postExecutionState;// 通过 cycleToPath 调用后面的生命周期cycleToPath(r, postExecutionState, shouldExcludeLastTransition);}// ...}
  • LaunchActivityItem 的 execute
    @Overridepublic void execute(ClientTransactionHandler client, IBinder token,PendingTransactionActions pendingActions) {Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,mPendingResults, mPendingNewIntents, mIsForward,mProfilerInfo, client);// 最终调用回了 ActivityThread 中的 handleLaunchActivityclient.handleLaunchActivity(r, pendingActions, null /* customIntent */);Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);}
  • 接下来 ActivityThread 中的 handleLaunchActivity 后就通过调用 mInstrumentation.newActivity进行创建, activity的attach onCreate方法等进行activity生命周期的开始。下面就不说了跟上面都一样了。

问题:为什么requestWindowFeature(Window.FEATURE_NO_TITLE);要在setContentView()之前.

  • 我们看一下setContentView的源码:在 installDecor() 的时候。
 @Overridepublic void setContentView(int layoutResID) {if (mContentParent == null) {// 创建DecorinstallDecor();} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {mContentParent.removeAllViews();}if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {// ...} else {mLayoutInflater.inflate(layoutResID, mContentParent);}// ...}
  • 在 installDecor(); 中
 private void installDecor() {mForceDecorInstall = false;if (mDecor == null) {// 如果是null new Decor// 当 new Decor()的时候需要传入 FeatureId 所以要在之前设置好才会能拿到用户自己设置的值。源码我就不贴出来了mDecor = generateDecor(-1);// ...} else {mDecor.setWindow(this);}if (mContentParent == null) {// 这里面会获取 Feature 的信息mContentParent = generateLayout(mDecor);// Set up decor part of UI to ignore fitsSystemWindows if appropriate.mDecor.makeOptionalFitsSystemWindows();final DecorContentParent decorContentParent = (DecorContentParent) mDecor.findViewById(R.id.decor_content_parent);if (decorContentParent != null) {mDecorContentParent = decorContentParent;mDecorContentParent.setWindowCallback(getCallback());if (mDecorContentParent.getTitle() == null) {mDecorContentParent.setWindowTitle(mTitle);}final int localFeatures = getLocalFeatures();for (int i = 0; i < FEATURE_MAX; i++) {if ((localFeatures & (1 << i)) != 0) {mDecorContentParent.initFeature(i);}}mDecorContentParent.setUiOptions(mUiOptions);if ((mResourcesSetFlags & FLAG_RESOURCE_SET_ICON) != 0 ||(mIconRes != 0 && !mDecorContentParent.hasIcon())) {mDecorContentParent.setIcon(mIconRes);} else if ((mResourcesSetFlags & FLAG_RESOURCE_SET_ICON) == 0 &&mIconRes == 0 && !mDecorContentParent.hasIcon()) {mDecorContentParent.setIcon(getContext().getPackageManager().getDefaultActivityIcon());mResourcesSetFlags |= FLAG_RESOURCE_SET_ICON_FALLBACK;}if ((mResourcesSetFlags & FLAG_RESOURCE_SET_LOGO) != 0 ||(mLogoRes != 0 && !mDecorContentParent.hasLogo())) {mDecorContentParent.setLogo(mLogoRes);}PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, false);if (!isDestroyed() && (st == null || st.menu == null) && !mIsStartingWindow) {invalidatePanelMenu(FEATURE_ACTION_BAR);}} else {mTitleView = findViewById(R.id.title);if (mTitleView != null) {if ((getLocalFeatures() & (1 << FEATURE_NO_TITLE)) != 0) {final View titleContainer = findViewById(R.id.title_container);if (titleContainer != null) {titleContainer.setVisibility(View.GONE);} else {mTitleView.setVisibility(View.GONE);}mContentParent.setForeground(null);} else {mTitleView.setText(mTitle);}}}if (mDecor.getBackground() == null && mBackgroundFallbackResource != 0) {mDecor.setBackgroundFallback(mBackgroundFallbackResource);}// 判断 sFeature 的值if (hasFeature(FEATURE_ACTIVITY_TRANSITIONS)) {if (mTransitionManager == null) {final int transitionRes = getWindowStyle().getResourceId(R.styleable.Window_windowContentTransitionManager,0);if (transitionRes != 0) {final TransitionInflater inflater = TransitionInflater.from(getContext());mTransitionManager = inflater.inflateTransitionManager(transitionRes,mContentParent);} else {mTransitionManager = new TransitionManager();}}mEnterTransition = getTransition(mEnterTransition, null,R.styleable.Window_windowEnterTransition);mReturnTransition = getTransition(mReturnTransition, USE_DEFAULT_TRANSITION,R.styleable.Window_windowReturnTransition);mExitTransition = getTransition(mExitTransition, null,R.styleable.Window_windowExitTransition);mReenterTransition = getTransition(mReenterTransition, USE_DEFAULT_TRANSITION,R.styleable.Window_windowReenterTransition);mSharedElementEnterTransition = getTransition(mSharedElementEnterTransition, null,R.styleable.Window_windowSharedElementEnterTransition);mSharedElementReturnTransition = getTransition(mSharedElementReturnTransition,USE_DEFAULT_TRANSITION,R.styleable.Window_windowSharedElementReturnTransition);mSharedElementExitTransition = getTransition(mSharedElementExitTransition, null,R.styleable.Window_windowSharedElementExitTransition);mSharedElementReenterTransition = getTransition(mSharedElementReenterTransition,USE_DEFAULT_TRANSITION,R.styleable.Window_windowSharedElementReenterTransition);if (mAllowEnterTransitionOverlap == null) {mAllowEnterTransitionOverlap = getWindowStyle().getBoolean(R.styleable.Window_windowAllowEnterTransitionOverlap, true);}if (mAllowReturnTransitionOverlap == null) {mAllowReturnTransitionOverlap = getWindowStyle().getBoolean(R.styleable.Window_windowAllowReturnTransitionOverlap, true);}if (mBackgroundFadeDurationMillis < 0) {mBackgroundFadeDurationMillis = getWindowStyle().getInteger(R.styleable.Window_windowTransitionBackgroundFadeDuration,DEFAULT_BACKGROUND_FADE_DURATION_MS);}if (mSharedElementsUseOverlay == null) {mSharedElementsUseOverlay = getWindowStyle().getBoolean(R.styleable.Window_windowSharedElementsUseOverlay, true);}}}}

所以需要在setContentView之前设置才会生效。

Android Application创建到Activity启动(launcher启动和startActivity启动)相关推荐

  1. Android系统默认Home应用程序 Launcher 的启动过程源代码分析

    分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow 也欢迎大家转载本篇文章.分享知识,造福人民,实现我们中华民族伟大复兴! 在前面一 ...

  2. Android学习羁绊之Activity

    原文链接:Android学习羁绊–>Activity Activity是Android系统的四大组件之一,Activity是用户可操作的可视化界面,为用户提供一个完成操作指令的窗口,一个Acti ...

  3. Android程序活动单元Activity

    Android程序活动单元Activity 目录 Android程序活动单元Activity 4.1 Activity的生命周期 4.1.1 生命周期状态 4.1.2 生命周期方法 4.2 Activ ...

  4. Android Activity的启动流程分析:以Launcher启动一个Activity为例,分析应用进程的创建、Activity的启动,以及他们和AMS之间的交互

    文章目录 一. Step1 - Step 11:Launcher通过Binder进程间通信机制通知ActivityManagerService,它要启动一个Activity: Step 1. Laun ...

  5. Activity启动流程(六)注册目标Activity进程到system_server进程以及创建目标Activity进程Application

    注册Activity应用进程到system_server以及创建Activity应用进程Application Android四大组件源码实现详解系列博客目录: Android应用进程创建流程大揭秘 ...

  6. 启动Activity的流程(Launcher中点击图标启动)

    启动Activity一般有多种方式,常见的有三种: 在Launcher桌面点击app图标 调用startActivity启动一个Activity 命令am start启动 这三种方式在服务端的处理方式 ...

  7. Android 深入研究之 ✨ Activity启动流程+Activity生命周期✨

    Activity分析目录 前言 Activity生命周期 1.activity的四个状态 2.activity的生命周期 3.activity优先级 Activity启动流程 Activity的启动流 ...

  8. Android系统启动流程(四)Launcher进程启动过程解析(附带面试题)

    前面我们分析了init进程,zygote进程,SystemServer进程,本篇的Launcher是系统启动流程的最后一个进程. 1 Launcher概述 Launcher进程是一个系统的应用程序,位 ...

  9. Android系统启动流程(四)Launcher启动过程与系统启动流程

    相关文章 Android系统架构与系统源码目录 Android系统启动流程(一)解析init进程启动过程 Android系统启动流程(二)解析Zygote进程启动过程 Android系统启动流程(三) ...

  10. Android初级开发笔记-- activity启动模式的学习(1)

    第一次学习Android中一个很重要的概念,启动模式.文章记录的也只是一些入门知识,随着学习的深入还会有activity启动模式的学习(2)和(3). 下面分三个小点说一下对启动模式的理解区别以及如何 ...

最新文章

  1. Linux C编程--线程操作1--线程概述和简单的线程操作
  2. python内置函数源码_如何查看python内置函数源码
  3. C#语言-07.文件操作
  4. c语言无符号中符号什么意思,C语言中无符号与有符号及相加问题
  5. 关于python的单线程和多线程
  6. 前端面试常见逻辑题收集及分析
  7. 剑指Offer - 面试题15. 二进制中1的个数(位运算)
  8. abaqus python 读取文件_通过Python脚本从Abaqus中的excel文件导入幅度数据
  9. 中兴连专利也不申请了?
  10. 【图像处理基础】基于matlab GUI图像局部放大【含Matlab源码 1016期】
  11. 1 使用WPE工具分析游戏网络封包
  12. DotNetBar2学习笔记-TabControl的使用
  13. ORACLE 中通过证件号码获取性别
  14. java字符串替换一部分_字符串中部分字符替换
  15. Unity移动的三种方式
  16. java实现小写转大写_人民币小写转大写(Java实现)
  17. Power BI 客户端 安装 错误
  18. Gartner发布《2023年十大战略技术趋势》
  19. 互联网公司发送短信为什么通过第三方短信平台,而不是通过运营商。
  20. 扫描仪产品国家抽检实施细则及信息技术类产品检测设备

热门文章

  1. 《人机交互技术》第四章 人机交互技术概述
  2. Python 分析《三国演义》看司马懿三父子如何用计谋干掉了曹操后代
  3. kvm文档翻译-第六章
  4. mysql初始化密码_MySQL5.7初始密码查看及重置
  5. 工欲善其事必先利其器-SpringBoot源码研究之源码编译
  6. Gym 100818F Irrational Roots (数学)
  7. 弹出登录框 您未被授权查看该页 的解决办法
  8. HTML5小游戏源码收藏
  9. Mybatis与JPA的优缺点
  10. jeecms oracle v5_jeecms v5 spring和ehcache的整合