从源码中理解Activity组件(3)-生命周期

前言

在前面的文章从AMS和PMS的相关源码分析了Activity相关的manifest解析到实例的反射构建,也分析了跟Activity相关的一些数据类,了解了Activity在AMS中是以ActivityRecord对象存在,又由Task将相关功能的ActivityRecord组织在一起,零零散散的记录了很多,除了这些,在开发中经常谈及Activity就会关联其生命周期,也知道Activity会由onCreate->onResume->onPaush->onStop->onDestory等生命周期流程,这篇文章就从源码的角度看看这些生命周期是怎么在哪里触发的

onCreate

这个流程在前面的文章中已经分析过了,简单的梳理流程就是当要启动一个Activity的时候是通过调用startActivity方法开始执行

->startActivity

->startActivityForResult

->Instrumentation.execStartActivity

->ATMS.startActivity

->ActivityStarter.execute

->ActivityStackSupervisor.startSpecificActivity->realStartActivityLocked

这一系列的流程前面已经分析过,对于Activity创建过程中涉及的类和关键方法还是需要有一定的熟悉感,当执行到realStartActivityLocked方法中,里面就涉及到跟生命周期相关的代码执行了

//ActivityStackSupervisor.java
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
                                boolean andResume, boolean checkConfig) {
  //...省略部分源码
  
  //创建了一个ClientTransaction事务对象
  final ClientTransaction clientTransaction = ClientTransaction.obtain();
  //添加了一个LaunchActivityItem类型的callback
  clientTransaction.addCallback(LaunchActivityItem.obtain();
  
  //熟悉的Lifecycle生命周期相关的关键词
  final ActivityLifecycleItem lifecycleItem;
  if (andResume) {
    //可能跟onResume相关
    lifecycleItem = ResumeActivityItem.obtain();
  } else {
    //可能跟onPause相关
    lifecycleItem = PauseActivityItem.obtain();
  }
  //赋值了LifecycleStateRequest字段                              
  clientTransaction.setLifecycleStateRequest(lifecycleItem);
                                
  //mService就是ATMS
  //调用schedule执行事务
  mService.getLifecycleManager().scheduleTransaction(clientTransaction);
}

在startActivity的流程中,通过构造了一个ClientTransaction类型对象,传入了LaunchActivityItem的Callback,然后通过schedule方法进行执行,mService就是ATMS类型的成员变量,ClientLifecycleManager是一个功能类,里面有scheduleTransaction方法的执行

class ClientLifecycleManager {
    void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
      //IApplicationThread在前面的文章中分析过,就是ActivityThread跟AMS通信的代理
      //可以理解为ActivityThread对象
      final IApplicationThread client = transaction.getClient();
      //执行到了ClientTransaction的schedule
      transaction.schedule();
      if (!(client instanceof Binder)) {
        transaction.recycle();
      }
    }
}

public class ClientTransaction implements Parcelable, ObjectPoolItem {
    //同上,IApplicationThread就代表了ActivityThread对象
    private IApplicationThread mClient;
  
    public void schedule() throws RemoteException {
      //执行到了ActivityThread中的方法
      mClient.scheduleTransaction(this);
    }
}

//在ActivityThread中
private class ApplicationThread extends IApplicationThread.Stub {
    @Override
    public void scheduleTransaction(ClientTransaction transaction){
      //执行到了ActivityThread的父类的scheduleTransaction方法
      ActivityThread.this.scheduleTransaction(transaction);
    }
}

//public final class ActivityThread extends ClientTransactionHandler {}
//ActivityThread的父类
public abstract class ClientTransactionHandler {
    void scheduleTransaction(ClientTransaction transaction) {
      transaction.preExecute(this);
      //熟悉的handler-message通信
      //执行到ActivityThread内部的H回调
      sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }
}

class H extends Handler {
    public void handleMessage(Message msg) {
      case EXECUTE_TRANSACTION:
      final ClientTransaction transaction = (ClientTransaction) msg.obj;
      //执行到事务处理的Executor对象的方法
      mTransactionExecutor.execute(transaction);
      if (isSystem()) {
        transaction.recycle();
      }
      break;
    }
}

public class TransactionExecutor {
    public void execute(ClientTransaction transaction) {
      //执行内部的callbacks
      executeCallbacks(transaction);
      //执行LifecycleState
      executeLifecycleState(transaction);
    }
  
    public void executeCallbacks(ClientTransaction transaction) {
      //取出ClientTransaction中设置的callbacks
      final List callbacks = transaction.getCallbacks();
      final int size = callbacks.size();
      for (int i = 0; i < size; ++i) {
        //取出具体的ClientTransactionItem
        final ClientTransactionItem item = callbacks.get(i);
        //执行对应的execute方法
        item.execute(mTransactionHandler, token, mPendingActions);
        item.postExecute(mTransactionHandler, token, mPendingActions);
      }
    }
  
    private void executeLifecycleState(ClientTransaction transaction) {
      //在设置了Callback后又设置了一个LifecycleStateRequest
      final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
      lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
      lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
    }
}

通过一系列的方法转发,最终执行到我们在前面设置的Callback对象LaunchActivityItem的execute方法,然后后一步会去执行ResumeActivityItem的execute方法

//LaunchActivityItem.java
public class LaunchActivityItem extends ClientTransactionItem {
    @Override
    //ClientTransactionHandler这个对象就ActivityThread
    public void execute(ClientTransactionHandler client, IBinder token,
                        PendingTransactionActions pendingActions) {
      ActivityClientRecord r = new ActivityClientRecord();
      //又执行到了ActivityThread对象中
      client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
    }
}

//ResumeActivityItem.java
public class ResumeActivityItem extends ActivityLifecycleItem {
    @Override
    public void execute(ClientTransactionHandler client, IBinder token,
                        PendingTransactionActions pendingActions) {
      //同上,执行到了ActivityThread对象中
      client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward,
                                  "RESUME_ACTIVITY");
    }
}

//ActivityThread.java
@Override
public Activity handleLaunchActivity() {
  //执行到performLaunch方法,这个方法就很熟悉了
  final Activity a = performLaunchActivity(r, customIntent);
  return a;
}

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    Activity activity = null;
    try {
      //通过反射构件Activity实例
      java.lang.ClassLoader cl = appContext.getClassLoader();
      activity = mInstrumentation.newActivity(
        cl, component.getClassName(), r.intent);
    }
    if (activity != null) {
      //调用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,
                      r.assistToken);

      if (r.isPersistable()) {
        //调用Instrumentation的callActivityOnCreate的方法
        mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
      } else {
        mInstrumentation.callActivityOnCreate(activity, r.state);
      }
      r.activity = activity;
    }
  //设置了state为ON_CREATE
  r.setState(ON_CREATE);
}

//Instrumentation.java
public void callActivityOnCreate(Activity activity, Bundle icicle) {
    prePerformCreate(activity);
    //调用到Activity的performCreate方法
    activity.performCreate(icicle);
    postPerformCreate(activity);
}
//Activity.java
final void performCreate(Bundle icicle) {
    performCreate(icicle, null);
}
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
    if (persistentState != null) {
      onCreate(icicle, persistentState);
    } else {
      //调用到我们熟悉的Activity内部的onCreate回调
      onCreate(icicle);
    }
}

可以看到LaunchActivityItem的execute方法中,通过反射构建了Activity的实例,并通过一系列的对象调用,执行到了Activity的onCreate方法

接下来分析ResumeActivityItem后续的方法

//ActivityThread.java
public void handleResumeActivity() {
  //这个方法会回调onResume方法
  final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
  
  final Activity a = r.activity;
  if (r.window == null && !a.mFinished && willBeVisible) {
    r.window = r.activity.getWindow();
    View decor = r.window.getDecorView();
    decor.setVisibility(View.INVISIBLE);
    ViewManager wm = a.getWindowManager();
    WindowManager.LayoutParams l = r.window.getAttributes();
    a.mDecor = decor;
    l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
    l.softInputMode |= forwardBit;
    if (a.mVisibleFromClient) {
      if (!a.mWindowAdded) {
        a.mWindowAdded = true;
        //这个位置回去添加视图,具体decor和wm在后面文章分析
        wm.addView(decor, l);
      }
    }
  } 
}
//继续执行perform方法
public ActivityClientRecord performResumeActivity() {
  final ActivityClientRecord r = mActivities.get(token);
  //执行到Activity的performResume方法
  r.activity.performResume(r.startsNotResumed, reason);
  return r;
}

//Activity.java
final void performResume(boolean followedByPause, String reason) {
  dispatchActivityPreResumed();
  //先执行了start这个方法
  performRestart(true /* start */, reason);
  mInstrumentation.callActivityOnResume(this);
}

final void performRestart(boolean start, String reason) {
  if (mStopped) {
    //如果当前页面调用了onStop()
    mStopped = false;
    mCalled = false;
    //这个方法就是回调声明周期onRestart
    mInstrumentation.callActivityOnRestart(this);
    if (start) {
      //这个调用到了onStart
      performStart(reason);
    }
  }
}

//Instrumentation.java
//上面方法的第一处注释调用
public void callActivityOnRestart(Activity activity) {
  activity.onRestart();
}

//Activity.java
final void performStart(String reason) {
  mInstrumentation.callActivityOnStart(this);
}

//Instrumentation.java
public void callActivityOnStart(Activity activity) {
  //onStart生命周期回调
  activity.onStart();
}

public void callActivityOnResume(Activity activity) {
  activity.mResumed = true;
  //回调Activity的onResume生命周期
  activity.onResume();
}

通过上面几个生命周期执行流程的源码分析,基本流程涉及的对象都是一样的,通过ActivityThread中的handleXXXActivity方法执行到相应的performXXXActivity方法,然后会执行到Instrumentation中的callActivityXXX方法,然后就会执行到Activity的具体XXX生命周期方法。

到这里找到了onCreat的调用位置,也找到了当页面onStop后,会调用onRestart->onStart的过程,也看到了后续的onResume的调用位置,但是熟悉生命周期流程的都知道,在onCreat->onResume之间,还会有一个onStart的调用,但是上面追溯的流程中,onStart的调用是当执行onStop后,从onRestart开始触发的,所以还得继续找一下onStart的执行位置

回到前面调用LaunchActivityItem和ResumeActivityItem的地方

//TransactionExecutor.java
private void executeLifecycleState(ClientTransaction transaction) {
  //前面分析拿到的就是ResumeActivityItem.java
  final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();

  //在onResume之前执行了这个方法
  cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);

  //前面分析了这个execute流程会执行到onResume方法
  lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
}

private void cycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState,
                         ClientTransaction transaction) {
  final int start = r.getLifecycleState();
  //拿到一个path值,后面会分析
  final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
  //会继续执行到这个方法
  performLifecycleSequence(r, path, transaction);
}

//这个方法看起来都是很熟悉的生命周期的方法
import static android.app.servertransaction.ActivityLifecycleItem.ON_CREATE;
import static android.app.servertransaction.ActivityLifecycleItem.ON_DESTROY;
import static android.app.servertransaction.ActivityLifecycleItem.ON_PAUSE;
import static android.app.servertransaction.ActivityLifecycleItem.ON_RESTART;
import static android.app.servertransaction.ActivityLifecycleItem.ON_RESUME;
import static android.app.servertransaction.ActivityLifecycleItem.ON_START;
import static android.app.servertransaction.ActivityLifecycleItem.ON_STOP;
import static android.app.servertransaction.ActivityLifecycleItem.PRE_ON_CREATE;
import static android.app.servertransaction.ActivityLifecycleItem.UNDEFINED;
private void performLifecycleSequence(ActivityClientRecord r, IntArray path,
                                      ClientTransaction transaction) {
  final int size = path.size();
  for (int i = 0, state; i < size; i++) {
    //通过拿到一个state,不同的生命周期可以拿到不同的state
    state = path.get(i);
    //mTransactionHandler这个对象其实就是ActivityThread
    //根据前面的流程会从ActivityThread执行对应的handleXXXActivity方法
    switch (state) {
      case ON_CREATE:
        mTransactionHandler.handleLaunchActivity();
        break;
      case ON_START:
        mTransactionHandler.handleStartActivity();
        break;
      case ON_RESUME:
        mTransactionHandler.handleResumeActivity();
        break;
      case ON_PAUSE:
        mTransactionHandler.handlePauseActivity();
        break;
      case ON_STOP:
        mTransactionHandler.handleStopActivity();
        break;
      case ON_DESTROY:
        mTransactionHandler.handleDestroyActivity();
        break;
      case ON_RESTART:
        mTransactionHandler.performRestartActivity();
        break;
      default:
        throw new IllegalArgumentException();
    }
  }
}

//可以看到这些生命周期状态是按了我们平时所熟知的顺序
public abstract class ActivityLifecycleItem extends ClientTransactionItem {
  public @interface LifecycleState{}
  public static final int UNDEFINED = -1;
  public static final int PRE_ON_CREATE = 0;
  public static final int ON_CREATE = 1;
  public static final int ON_START = 2;
  public static final int ON_RESUME = 3;
  public static final int ON_PAUSE = 4;
  public static final int ON_STOP = 5;
  public static final int ON_DESTROY = 6;
}

通过分析,发现在ResumeActivtyItem执行execute方法之前,调用了一个cycleToPath()方法,看起来跟生命周期相关,而且在具体的执行流程中会调用到对应的handleXXX方法,那么这个具体的path值对应的是什么

//在TransactionExecutor对象内的成员变量
private TransactionExecutorHelper mHelper = new TransactionExecutorHelper();

//执行到对应的getLifecyclePath方法
private IntArray mLifecycleSequence = new IntArray(6);
public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) {
        mLifecycleSequence.clear();
        if (finish >= start) {
          //正向生命周期递增
            if (start == ON_START && finish == ON_STOP) {
                // A case when we from start to stop state soon, we don't need to go
                // through the resumed, paused state.
                mLifecycleSequence.add(ON_STOP);
            } else {
                // just go there
                //mLifecycleSequence是一个6位的数组
                //将状态递增后保存在IntArray中
                for (int i = start + 1; i <= finish; i++) {
                    mLifecycleSequence.add(i);
                }
            }
        } else { // finish < start, can't just cycle down
          //反向生命周期回溯
            if (start == ON_PAUSE && finish == ON_RESUME) {
                mLifecycleSequence.add(ON_RESUME);
            } else if (start <= ON_STOP && finish >= ON_START) {
                for (int i = start + 1; i <= ON_STOP; i++) {
                    mLifecycleSequence.add(i);
                }
                // Restart
                mLifecycleSequence.add(ON_RESTART);
                // Go to required state
                for (int i = ON_START; i <= finish; i++) {
                    mLifecycleSequence.add(i);
                }
            } else {
                for (int i = start + 1; i <= ON_DESTROY; i++) {
                    mLifecycleSequence.add(i);
                }
                for (int i = ON_CREATE; i <= finish; i++) {
                    mLifecycleSequence.add(i);
                }
            }
        }

        // Remove last transition in case we want to perform it with some specific params.
        if (excludeLastState && mLifecycleSequence.size() != 0) {
            mLifecycleSequence.remove(mLifecycleSequence.size() - 1);
        }

        return mLifecycleSequence;
    }

通过上面的流程可以分析,在performLauchActivity方法中,通过r.setState(ON_CREATE)方法,设置了起始状态位ON_CREATE,ResumeActivityItem的targetState就是ON_RESUME,所以在cycleToPath方法后的数组里面的状态就是一个ON_START,所以,就会执行到对应的mTransactionHandler.handleStartActivity()方法中

//ActivityThread.java
public void handleStartActivity(IBinder token, PendingTransactionActions pendingActions) {
  //里面会继续回调到对应的instrumentation对应的方法中,最终执行onStart回调
  activity.performStart("handleStartActivity");
  //设置状态为ON_START
  r.setState(ON_START);
    //更新设置了Activity的可见性为true
  updateVisibility(r, true /* show */);
  mSomeActivitiesChanged = true;
}

private void updateVisibility(ActivityClientRecord r, boolean show) {
  View v = r.activity.mDecor;
  if (v != null) {
    if (show) {
      if (!r.activity.mVisibleFromServer) {
        r.activity.mVisibleFromServer = true;
        mNumVisibleActivities++;
        if (r.activity.mVisibleFromClient) {
          //遍历设置Acitivity的可见性为可见
          r.activity.makeVisible();
        }
      }
    }
  }
}

这个位置也验证了我们熟悉的知识点,在onCreate方法调用后Activity还处于不可见的状态,在onStart调用后,Activity处于用户可见的状态,但是没有焦点,还不能交互,只有在onResume方法调用后,当前的Activity才是可见可交互的,onResume中会添加View到window中

最后贴上Android官方的一个Activity生命周期状态图


activity_lifecycle.png
总结

通过一些列的绕来绕去的对象直接方法的调用,基本上摸清楚了Activity的生命周期函数回调的触发位置,通过生命周期事务类进行执行触发并且会有按周期顺序排列的状态序,从源码也能更直观的了解到,当onCreate执行的时候,视图对象是还没有显示出来的,所以经常会有说在oncreate中去活动view的width和height拿不到的情况,应该压根都还没有加载到根视图去测量绘制。

坚持写文章好难,这一次又断跟了一个季度,抽空考了个软考的架构师,现在有时间了,希望能继续更新下去

你可能感兴趣的:(从源码中理解Activity组件(3)-生命周期)