startActivity源码分析2

Android  源码分析  2023年11月17日 am8:09发布11个月前更新 91es.com站长
61 0 0

前言

简单记录一下startActivity()源码的启动过程,主要是过一下流程,细节太多顾不上。

接上回《startActivity源码分析》,启动新的Activity需要fork一个进程处理,经过一系列的操作,最后进入ActivityThread.java的main(),然后进行绑定进程。

这部分只要涉及如下源码流程分析

  1. Application的启动

  2. Activity.onCreate()

  3. Activity.onStart() 部分

  4. Activity.onResume()部分

PS : 只是个人走走流程,写的层级不够清晰。

正文

ActivityThread.java

main()
public static void main(String[] args) {
    CloseGuard.setEnabled(false);
    Environment.initForCurrentUser();
    EventLogger.setReporter(new EventLoggingReporter());
    final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
    TrustedCertificateStore.setDefaultUserDirectory(configDir);
    Process.setArgV0("<pre-initialized>")
    Looper.prepareMainLooper();
    long startSeq = 0;
    //创建一个ActivityThread
    ActivityThread thread = new ActivityThread();
    //[重]这里执行了attach()
    thread.attach(false, startSeq);
    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }
    //进入循环,正常情况不会退出的
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}
attach()
private void attach(boolean system, long startSeq) {
    sCurrentActivityThread = this;
    mSystemThread = system;
    //传入的system为false
    if (!system) {
        //略
        //这里获取的是ActivityManagerService
        final IActivityManager mgr = ActivityManager.getService();
        try {
            //[重]进行attach
            mgr.attachApplication(mAppThread, startSeq);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
        // Watch for getting close to heap limit.
        //略
    } else {
        //略
    }
    //略
}

ActivityManagerService.java

attachApplication()
@Override
public final void attachApplication(IApplicationThread thread, long startSeq) {
    synchronized (this) {
        //略
        attachApplicationLocked(thread, callingPid, callingUid, startSeq);
        //略
    }
}
attachApplicationLocked()
@GuardedBy("this")
private final boolean attachApplicationLocked(IApplicationThread thread,
        int pid, int callingUid, long startSeq) {
    ProcessRecord app;
    if (pid != MY_PID && pid >= 0) {
        synchronized (mPidsSelfLocked) {
            app = mPidsSelfLocked.get(pid);
        }
    } else {
        app = null;
    }
   // app不为null
    if (app == null && startSeq > 0) {
        final ProcessRecord pending = mPendingStarts.get(startSeq);
        if (pending != null && pending.startUid == callingUid
                && handleProcessStartedLocked(pending, pid, pending.usingWrapper,
                        startSeq, true)) {
            app = pending;
        }
    }
    if (app == null) {
        //略
        return false;
    }
    //app.thread为null
    if (app.thread != null) {
        handleAppDiedLocked(app, true, true);
    }
    //略
    try {
        //略
        //null
        if (app.isolatedEntryPoint != null) {
            thread.runIsolatedEntryPoint(app.isolatedEntryPoint, app.isolatedEntryPointArgs);
        } else if (app.instr != null) {
            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);
        }
        //略
    } catch (Exception e) {
        //略
        return false;
    }
    //略
    //normalMode为true
    if (normalMode) {
        try {
            //[重]调用attachApplicationLocked
            if (mStackSupervisor.attachApplicationLocked(app)) {
                didSomething = true;
            }
        } catch (Exception e) {
            badApp = true;
        }
    }
    //略
    return true;
}

上面有两个关注点

//第一个
thread.bindApplication()
//第二个
mStackSupervisor.attachApplicationLocked()

先看第一个,thread.bindApplication()方法。

ActivityThread.java

bindApplication()
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) {
    //services不为null
    if (services != null) {
        //初始化服务,services包含很多服务
        //这里不关注哈
        ServiceManager.initServiceCache(services);
    }
    //发送SET_CORE_SETTINGS
    setCoreSettings(coreSettings);
    //略
    //发送BIND_APPLICATION
    sendMessage(H.BIND_APPLICATION, data);
}

初始化服务后发送两个消息SET_CORE_SETTINGS和BIND_APPLICATION。

这里关注BIND_APPLICATION消息

handleMessage()
public void handleMessage(Message msg) {
    switch (msg.what) {
        case BIND_APPLICATION:
            AppBindData data = (AppBindData)msg.obj;
            handleBindApplication(data);
            break;
        //略
    }
}
handleBindApplication()

看字面意思,就是Application的绑定,也就是Application.onCreate()的启动。

//关注重点,这里就是Application的启动
private void handleBindApplication(AppBindData data) {
    //略
    //设置进程名
    Process.setArgV0(data.processName);
    //略
    LocaleList.setDefault(data.config.getLocales());
    //略
    updateDefaultDensity();
     //略
    final IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
    //b不为null
    if (b != null) {
        final IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
        try {
            final ProxyInfo proxyInfo = service.getProxyForNetwork(null);
            Proxy.setHttpProxySystemProperty(proxyInfo);
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    }
    //略
    //创建上下文环境
    final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
    updateLocaleListFromAppContext(appContext,
            mResourcesManager.getConfiguration().getLocales());
    //略
    //上面赋值过,ii为 null
    if (ii != null) {
        //略
    } else {
        //创建Instrumentation对象
        mInstrumentation = new Instrumentation();
        mInstrumentation.basicInit(this);
    }

    //略
    Application app;
    try {
        app = data.info.makeApplication(data.restrictedBackupMode, null);
        app.setAutofillCompatibilityEnabled(data.autofillCompatibilityEnabled);
        mInitialApplication = app;
        //略
        try {
            //调用onCreate(),其实也没做啥,应该是提前初始化
            mInstrumentation.onCreate(data.instrumentationArgs);
        }
        catch (Exception e) {
            throw new RuntimeException(
                "Exception thrown in onCreate() of "
                + data.instrumentationName + ": " + e.toString(), e);
        }
        try {
            //[重点]调用Application.onCreate()方法
            //执行到这里,就表示启动App的Application的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 (data.appInfo.targetSdkVersion < Build.VERSION_CODES.O_MR1
                || StrictMode.getThreadPolicy().equals(writesAllowedPolicy)) {
            StrictMode.setThreadPolicy(savedPolicy);
        }
    }
    //略
}

至此,Application的onCreate()已经执行完成。接着就是启动Activity啦。

回到上面,看第二个方法

mStackSupervisor.attachApplicationLocked()

ActivityStackSupervisor.java

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();
			//存在一个即将启动的,也就是我们启动的Activity
            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 {
						//[重]看名字就知道啥意思
						//真正启动Activity的方法
                        if (realStartActivityLocked(activity, app,
                            top == activity /* andResume */, true /* checkConfig */)) {
                            didSomething = true;
                        }
                    } catch (RemoteException e) {
                        throw e;
                    }
                }
            }
        }
    }
    if (!didSomething) {
        ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
    }
    return didSomething;
}

有一个满足条件,进入realStartActivityLocked()

realStartActivityLocked()

看名字,意思就是真正启动Activity的地方

final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
        boolean andResume, boolean checkConfig) throws RemoteException {
	//略
    try {
		//略
		//为true
        if (checkConfig) {
			//就是遍历,不看
            ensureVisibilityAndConfig(r, r.getDisplayId(),
                    false /* markFrozenIfConfigChanged */, true /* deferResume */);
        }
        if (r.getStack().checkKeyguardVisibility(r, true /* shouldBeVisible */,
                true /* isTop */)) {
            r.setVisibility(true);
        }
		//略
        try {
            final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
                    r.appToken);
			//[重]addCallback()
			//LaunchActivityItem这里初始化了
            clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                    System.identityHashCode(r), r.info,
                    mergedConfiguration.getGlobalConfiguration(),
                    mergedConfiguration.getOverrideConfiguration(), r.compat,
                    r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
                    r.persistentState, results, newIntents, mService.isNextTransitionForward(),
                    profilerInfo));
            final ActivityLifecycleItem lifecycleItem;
			//创建ResumeActivityItem
			//添加的是ResumeActivityItem
            if (andResume) {
                lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
            } else {
                lifecycleItem = PauseActivityItem.obtain();
            }
			//lifecycleItem是ResumeActivityItem对象
			//[重]setLifecycleStateRequest
            clientTransaction.setLifecycleStateRequest(lifecycleItem);
			//ClientLifecycleManager和 ClientTransactionHandler来辅助管理Activity生命周期
            // 他会发送EXECUTE_TRANSACTION消息到ActivityThread.H里面继续处理。
            //[重]
            mService.getLifecycleManager().scheduleTransaction(clientTransaction);
            if ((app.info.privateFlags & ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0
                    && mService.mHasHeavyWeightFeature) {
				//略
            }
        } catch (RemoteException e) {
			//略
        }
    } finally {
        endDeferResume();
    }
	//略
	//true
    if (andResume && readyToResume()) {
		//走这里
        stack.minimalResumeActivityLocked(r);
    } else {
        r.setState(PAUSED, "realStartActivityLocked");
    }
	//略
    return true;
}

上面主要关注如下几点

1. clientTransaction.addCallback();添加的LaunchActivityItem对象
2. clientTransaction.setLifecycleStateRequest();设置的ResumeActivityItem对象
3. mService.getLifecycleManager().scheduleTransaction(clientTransaction);执行上面安排的事务

最终要的是第三步

1. mService是ActivityManagerService对象
2. mService.getLifecycleManager()
ClientLifecycleManager getLifecycleManager() {
    return mLifecycleManager;
}
返回的是ClientLifecycleManager对象

之前暂停Launcher的Activity时也是这么执行的。

ClientLifecycleManager.java

scheduleTransaction()
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    final IApplicationThread client = transaction.getClient();
    transaction.schedule();
    if (!(client instanceof Binder)) {
        transaction.recycle();
    }
}

ClientTransaction.java

schedule()
public void schedule() throws RemoteException {
	//mClient是一个IApplicationThread类型,
	//ActivityThread的内部类ApplicationThread派生这个接口类并实现了对应的方法。
    mClient.scheduleTransaction(this);
}

ActivityThread.java

ApplicationThread.scheduleTransaction()
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
	//ActivityThread没有实现,那就找他父类ClientTransactionHandler
    ActivityThread.this.scheduleTransaction(transaction);
}

ClientTransactionHandler.java

scheduleTransaction()
void scheduleTransaction(ClientTransaction transaction) {
	//[1]先执行preExecute
	//pre其实就是提前初始化而已,可以略过,当然看看也无妨
    transaction.preExecute(this);
	//[2]这里发送,然后ActivityThread中处理
    sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}

先分析[1],然后在继续分析[2]

ClientTransaction.java

preExecute()
public void preExecute(android.app.ClientTransactionHandler clientTransactionHandler) {
	//上面[realStartActivityLocked]中添加了LaunchActivityItem对象
	//所以这里不为null
    if (mActivityCallbacks != null) {
        final int size = mActivityCallbacks.size();
        for (int i = 0; i < size; ++i) {
        	//[重]会执行LaunchActivityItem.preExecute()
            mActivityCallbacks.get(i).preExecute(clientTransactionHandler, mActivityToken);
        }
    }
    //上面设置了值ResumeActivityItem对象
    if (mLifecycleStateRequest != null) {
    	//[重]会执行ResumeActivityItem.preExecute()
        mLifecycleStateRequest.preExecute(clientTransactionHandler, mActivityToken);
    }
}

由于pre中涉及内容不是我们关心重点,不继续跟进。

ClientTransactionHandler.java

接上面

void scheduleTransaction(ClientTransaction transaction) {
	//先执行preExecute
    transaction.preExecute(this);
	//这里发送,然后ActivityThread中处理
    sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}

刚分析完transaction.preExecute(this),接着就是EXECUTE_TRANSACTION消息的发送啦

sendMessage()
abstract void sendMessage(int what, Object obj);

抽象函数,那就是找它的子类

ActivityThread.java

sendMessage()
void sendMessage(int what, Object obj) {
    sendMessage(what, obj, 0, 0, false);
}

private void sendMessage(int what, Object obj, int arg1) {
    sendMessage(what, obj, arg1, 0, false);
}

private void sendMessage(int what, Object obj, int arg1, int arg2) {
    sendMessage(what, obj, arg1, arg2, false);
}

private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
    Message msg = Message.obtain();
    msg.what = what;
    msg.obj = obj;
    msg.arg1 = arg1;
    msg.arg2 = arg2;
    if (async) {
        msg.setAsynchronous(true);
    }
    mH.sendMessage(msg);
}
handleMessage()
public void handleMessage(Message msg) {
    switch (msg.what) {
		//略
        case EXECUTE_TRANSACTION: //ClientTransactionHandler.java
            final ClientTransaction transaction = (ClientTransaction) msg.obj;
            mTransactionExecutor.execute(transaction);
            if (isSystem()) {
                transaction.recycle();
            }
            break;
    }
    Object obj = msg.obj;
    if (obj instanceof SomeArgs) {
        ((SomeArgs) obj).recycle();
    }
}

TransactionExecutor.java

execute()
public void execute(ClientTransaction transaction) {
    final IBinder token = transaction.getActivityToken();
	//[重]
    executeCallbacks(transaction);
	//[重]
    executeLifecycleState(transaction);
    mPendingActions.clear();
}

这里分两步

//1
executeCallbacks(transaction);
//2
executeLifecycleState(transaction);

我们先看1

executeCallbacks()
@VisibleForTesting
public void executeCallbacks(ClientTransaction transaction) {
	//略
    final int size = callbacks.size();
	//此时size  1
    for (int i = 0; i < size; ++i) {
        final ClientTransactionItem item = callbacks.get(i);
        final int postExecutionState = item.getPostExecutionState();
        final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,
                item.getPostExecutionState());
        if (closestPreExecutionState != UNDEFINED) {
            cycleToPath(r, closestPreExecutionState);
        }
		//[重] LaunchActivityItem.execute()
        item.execute(mTransactionHandler, token, mPendingActions);
		//postExecute()没有重新,,,略过
        item.postExecute(mTransactionHandler, token, mPendingActions);
        if (r == null) {
            r = mTransactionHandler.getActivityClient(token);
        }
        //略
    }
}

我们这里知关心

item.execute(mTransactionHandler, token, mPendingActions);

LaunchActivityItem.java

execute()
@Override
public void execute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
            mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
            mPendingResults, mPendingNewIntents, mIsForward,
            mProfilerInfo, client);
    //[重]关注这个,处理LaunchActivity,也就是我们常见的onCreate()周期
    //client是ClientTransactionHandler,看他子类哈ActivityThread
    client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
}

ActivityThread.java

handleLaunchActivity()
public Activity handleLaunchActivity(ActivityClientRecord r,
        PendingTransactionActions pendingActions, Intent customIntent) {
	//略
    final Activity a = performLaunchActivity(r, customIntent);
	//略
    return a;
}
performLaunchActivity()
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
	//略
    ContextImpl appContext = createBaseContextForActivity(r);
    Activity activity = null;
    try {
        java.lang.ClassLoader cl = appContext.getClassLoader();
		//创建Activity
        activity = mInstrumentation.newActivity(
                cl, component.getClassName(), r.intent);
		//略
    } catch (Exception e) {
		//略
    }
    try {
        Application app = r.packageInfo.makeApplication(false, mInstrumentation);
        if (activity != null) {
            CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
            Configuration config = new Configuration(mCompatConfiguration);
            if (r.overrideConfig != null) {
                config.updateFrom(r.overrideConfig);
            }
            Window window = null;
			//略
            appContext.setOuterContext(activity);
			//activity绑定window,具体自己看
            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);
			//略
			//false
            if (r.isPersistable()) {
                mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
            } else {
				//[重]调用OnCreate()
				//这里调用的onCreate()把mCalled置为true
                mInstrumentation.callActivityOnCreate(activity, r.state);
            }
            r.activity = activity;
        }
		//更新状态
        r.setState(ON_CREATE);
        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;
}

这里只关心

mInstrumentation.callActivityOnCreate(activity, r.state);

Instrumentation.java

callActivityOnCreate()
public void callActivityOnCreate(Activity activity, Bundle icicle) {
    prePerformCreate(activity);
	//[重]关心performCreate()
    activity.performCreate(icicle);
    postPerformCreate(activity);
}

Activity.java

performCreate()
final void performCreate(Bundle icicle) {
    performCreate(icicle, null);
}
performCreate()
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
    mCanEnterPictureInPicture = true;
    restoreHasCurrentPermissionRequest(icicle);
	//persistentState= null
    if (persistentState != null) {
        onCreate(icicle, persistentState);
    } else {
        onCreate(icicle);
    }
    mActivityTransitionState.readState(icicle);
    mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
            com.android.internal.R.styleable.Window_windowNoDisplay, false);
    mFragments.dispatchActivityCreated();
    mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
}
onCreate()
@MainThread
@CallSuper
protected void onCreate(@Nullable Bundle savedInstanceState) {
    if (mLastNonConfigurationInstances != null) {
        mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders);
    }
    if (mActivityInfo.parentActivityName != null) {
        if (mActionBar == null) {
            mEnableDefaultActionBarUp = true;
        } else {
            mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
        }
    }
    if (savedInstanceState != null) {
        mAutoFillResetNeeded = savedInstanceState.getBoolean(AUTOFILL_RESET_NEEDED, false);
        mLastAutofillId = savedInstanceState.getInt(LAST_AUTOFILL_ID,
                View.LAST_APP_AUTOFILL_ID);
        if (mAutoFillResetNeeded) {
            getAutofillManager().onCreate(savedInstanceState);
        }
        Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
        mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
                ? mLastNonConfigurationInstances.fragments : null);
    }
    mFragments.dispatchCreate();
    getApplication().dispatchActivityCreated(this, savedInstanceState);
    if (mVoiceInteractor != null) {
        mVoiceInteractor.attachActivity(this);
    }
    mRestoredFromBundle = savedInstanceState != null;
    mCalled = true;
}

此时onCreate()就启动完成了。

回到上面TransactionExecutor.java中的execute()中的第二部分

executeLifecycleState(transaction);

TransactionExecutor.java

executeLifecycleState()
private void executeLifecycleState(ClientTransaction transaction) {
    final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
	//为ResumeActivityItem对象,之前设置的
    if (lifecycleItem == null) {
        return;
    }
    final IBinder token = transaction.getActivityToken();
    final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
	//r是启动的Activity
    if (r == null) {
        return;
    }
	//[重]
    cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);
	//[重]执行ResumeActivityItem.execute()
    lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
	//ResumeActivityItem中重写了,可以看看
    lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}

这里关注三个方法

1. cycleToPath()
2. ResumeActivityItem.execute()
3. ResumeActivityItem.postExecute()
cycleToPath()
private void cycleToPath(ActivityClientRecord r, int finish,
        boolean excludeLastState) {
    final int start = r.getLifecycleState();
    final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
	//执行这个
    performLifecycleSequence(r, path);
}
performLifecycleSequence()
private void performLifecycleSequence(ActivityClientRecord r, IntArray path) {
    final int size = path.size();
    for (int i = 0, state; i < size; i++) {
        state = path.get(i);
        //此时状态是ON_START=2
        switch (state) {
            case ON_CREATE:
                mTransactionHandler.handleLaunchActivity(r, mPendingActions,
                        null /* customIntent */);
                break;
            case ON_START:
				//走这里,也就是处理onStart()周期
                mTransactionHandler.handleStartActivity(r, mPendingActions);
                break;
            case ON_RESUME:
                mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
                        r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
                break;
            case ON_PAUSE:
				Slog.e(TAG, "performLifecycleSequence 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);
        }
    }
}

这里的重点是onStart()生命周期的执行,具体看

mTransactionHandler.handleStartActivity(r, mPendingActions);
//就是ActivityThread.java
ActivityThread.handleStartActivity(r, mPendingActions);

由于暂时不关注这个,略过。

回到上面分析

ResumeActivityItem.execute()

ResumeActivityItem.java

execute()
@Override
public void execute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    // 看起子类ActivityThread.java
    client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward,
            "RESUME_ACTIVITY");
}

由于这部分还有一个源码分析用到,这里暂时不展开分析。

这部分暂时略哈,后面还有一个话题。也就是关于开机动画的退出分析。

postExecute()
@Override
public void postExecute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    try {
    	//调用的是ActivityManagerService.java中的
        ActivityManager.getService().activityResumed(token);
    } catch (RemoteException ex) {
        throw ex.rethrowFromSystemServer();
    }
}

至此,Activity进入onResume(),用户可以看见和操作了。

参考文章

 历史上的今天

  1. 2019: 韩少功:偷书(0条评论)
  2. 2018: Android内置应用更新或升级后被还原(0条评论)
  3. 2018: Settings中开发者模式的影藏和显示(0条评论)
版权声明 1、 本站名称: 91易搜
2、 本站网址: 91es.com3xcn.com
3、 本站内容: 部分来源于网络,仅供学习和参考,若侵权请留言
3、 本站申明: 个人流水账日记,内容并不保证有效

暂无评论

暂无评论...

随机推荐

MediaScanner源码JNI介绍

前言之前介绍MediaScanner源码时就知道这里用了JNI,学习完JNI后重跟一下MediaScanner的代码。记录一下本地方法的使用和调用Java方法,记录于此,方便自己查阅和复现。正文涉及文件或目录frameworks\base\media\java\android\media\...

[摘]Android混淆从入门到精通

前言本文摘抄,网上都写的很不错,我就摘抄于此。简介作为Android开发者,如果你不想开源你的应用,那么在应用发布前,就需要对代码进行混淆处理,从而让我们代码即使被反编译,也难以阅读。混淆概念虽然容易,但很多初学者也只是网上搜一些成型的混淆规则粘贴进自己项目,并没有对混淆有个深入的理解。本篇...

RecyclerView对Item拖动和上下滑动记录

前言简单的记录RecyclerView对Item的拖拽和上下滑动的使用。如果只是简单功能ListView就可以搞定,但是如果需要复杂点的,比如拖拽等,用recyclerview就可以完美解决。recyclerview可以借助ItemTouchHelper实现拖动和滑动删除功能,本文就简单的记...

朱以撒:浅色寂语

秋天来了,山野闪动着风吹过的暗影。叶片开始有秩序地脱离枝条,原先紧挨在一起的两片树叶,一片先下来了,另一片落下来的时候,再也见不到它旧日的邻居。交接的日子来临,一些矮小的灌木丛里,浆果外表抹上了一层紫黑,一只翠绿的螳螂举着带锯的刀,轻轻划了一下,浆水霎时奔涌而出,紫透了枝下的土皮。稻子已经进仓,秋...

[摘]Android中shape的用法详解

用代码生成图片,而且图片能随意的更改,既方便又节省空间,下面就介绍用shape生成自定义图形的方法步骤:在res/drawable下新建一个xml文件;在代码中引用这个xml文件,引用方式和图片一样。定义shape图形的语法如下:<?xml version="1.0" enc...

Android图片倒影记录

前言Android对图片进行倒影处理。也就是对底部进行一定高度的翻转。具体效果如图正文直接上代码<!-- layout_height= 倒影高度+分割线高度+图片高度,否则显示不全 --><com.biumall.reflectview.view.Reflect...