上篇文章 分析了点击桌面图标,启动Activity的过程分析,由于篇幅的原因,将Activity启动过程中,上一个Activity,也就是Launcher进程的Launcher这个Activity的OnPause方法未分析,这篇文章就分析Activity的OnPause方法的执行过程。接着上篇文章的ActivityStackSupervisor类的resumeTopActivityInnerLocked()进行分析,这个方法内部,会先检查是否存在resumedActivity,如果有就先执行resumedActivity的onPause方法,然后在执行要启动的Activity的流程。
http://androidxref.com/9.0.0_r3/xref/frameworks/base/services/core/java/com/android/server/am/ActivityStack.java
@GuardedBy("mService")
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
// 参入的两个参数都为null
// ...
//返回当前Activity栈中,未finish的,在顶部的Activity,也就是要启动的Activity,显然next不为null
final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
// hasRunningActivity = true
final boolean hasRunningActivity = next != null;
// ...
//判断不成立
if (!hasRunningActivity) {
return resumeTopActivityInNextFocusableStack(prev, options, "noMoreActivities");
}
next.delayedResume = false;
// ...
mStackSupervisor.setLaunchSource(next.info.applicationInfo.uid);
// ...
// 如果当前有处于Resume状态的Activity时,则先将这个Activity暂停(执行onPause方法)
// 比如在AcivityA中启动ActivityB(设置了ActivityB的process属性,ActivityB运行在一个新的进程中),那么
// 此时ActivityA就要执行onPause方法,在去为ActivityB创建一个app进程(如果ActivityB所属的进程不存在的话),
//如果ActivityB所在的进程存在,则直接启动ActivityB,下面的代码的逻辑,就是这样处理的
if (mResumedActivity != null) {
if (DEBUG_STATES) Slog.d(TAG_STATES,
"resumeTopActivityLocked: Pausing " + mResumedActivity);
pausing |= startPausingLocked(userLeaving, false, next, false);
}
// ...
ActivityStack lastStack = mStackSupervisor.getLastStack();
//如果要启动的Activity所属的进程存在
if (next.app != null && next.app.thread != null) {
//...
synchronized(mWindowManager.getWindowManagerLock()) {
// This activity is now becoming visible.
// ...
boolean notUpdated = true;
if (mStackSupervisor.isFocusedStack(this)) {
notUpdated = !mStackSupervisor.ensureVisibilityAndConfig(next, mDisplayId,
true /* markFrozenIfConfigChanged */, false /* deferResume */);
}
if (notUpdated) {
ActivityRecord nextNext = topRunningActivityLocked();
// ...
if (nextNext != next) {
// Do over!
//关键代码
mStackSupervisor.scheduleResumeTopActivities();
}
// ...
return true;
}
// ...
}
// ...
} else {
// Whoops, need to restart this activity!
//要启动的Activity所在的进程未创建
// ...
//关键代码
mStackSupervisor.startSpecificActivityLocked(next, true, true);
}
// ...
return true;
}
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
ActivityRecord resuming, boolean pauseImmediately) {
// ...
ActivityRecord prev = mResumedActivity;
// ...
if (prev.app != null && prev.app.thread != null) {
if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Enqueueing pending pause: " + prev);
try {
// ...
// 关键代码
mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken,
PauseActivityItem.obtain(prev.finishing, userLeaving,
prev.configChangeFlags, pauseImmediately));
}
// ...
} else {
// ...
}
// ...
if (mPausingActivity != null) {
// ...
if (pauseImmediately) {
// ...
completePauseLocked(false, resuming);
return false;
} else {
schedulePauseTimeout(prev);
return true;
}
} else {
// ...
if (resuming == null) {
mStackSupervisor.resumeFocusedStackTopActivityLocked();
}
return false;
}
}
startPausingLocked()这个方法中,会执行ClientLifecycleManager的scheduleTransaction方法,注意传入的第三个参数,是一个PauseActivityItem的实例对象,下面看这个方法的具体实现:
http://androidxref.com/9.0.0_r3/xref/frameworks/base/services/core/java/com/android/server/am/ClientLifecycleManager.java
void scheduleTransaction(@NonNull IApplicationThread client, @NonNull IBinder activityToken,
@NonNull ActivityLifecycleItem stateRequest) throws RemoteException {
final ClientTransaction clientTransaction = transactionWithState(client, activityToken,
stateRequest);
scheduleTransaction(clientTransaction);
}
private static ClientTransaction transactionWithState(@NonNull IApplicationThread client,
@NonNull IBinder activityToken, @NonNull ActivityLifecycleItem stateRequest) {
final ClientTransaction clientTransaction = ClientTransaction.obtain(client, activityToken);
// 关键点,这里的stateRequest,就是PauseActivityItem类型的对象
clientTransaction.setLifecycleStateRequest(stateRequest);
return clientTransaction;
}
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
final IApplicationThread client = transaction.getClient();
transaction.schedule();
if (!(client instanceof Binder)) {
transaction.recycle();
}
}
scheduleTransaction方法经过重载方法后,调用了ClientTransaction的schedule方法,下面看看这个方法的具体实现:
http://androidxref.com/9.0.0_r3/xref/frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
这个方法中的mClient是一个IApplicationThread类型的对象,它其实就是一个adil接口,它的具体实现类是ApplicationThread,这样代码就跳转到了ApplicationThread类中执行,下面看看ApplicationThread的scheduleTransaction方法的具体实现:
http://androidxref.com/9.0.0_r3/xref/frameworks/base/core/java/android/app/ActivityThread.java
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
这个方法内部又调用了ClientTransactionHandler类的scheduleTransaction方法,下面看看这个方法的具体实现:
http://androidxref.com/9.0.0_r3/xref/frameworks/base/core/java/android/app/ClientTransactionHandler.java
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
这个方法内部调用了ActivityThread类的sendMessage方法,ActivityThread类的内部类H是继承Handler的,最后会执行H类的handleMessage方法
// ...
case EXECUTE_TRANSACTION:
final ClientTransaction transaction = (ClientTransaction) msg.obj;
mTransactionExecutor.execute(transaction);
if (isSystem()) {
transaction.recycle();
}
break;
// ...
这个方法内部又调用了TransactionExecutor的execute方法,下面看看这个方法的具体实现:
http://androidxref.com/9.0.0_r3/xref/frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
public void execute(ClientTransaction transaction) {
final IBinder token = transaction.getActivityToken();
executeCallbacks(transaction);
executeLifecycleState(transaction);
mPendingActions.clear();
}
public void executeCallbacks(ClientTransaction transaction) {
final List callbacks = transaction.getCallbacks();
if (callbacks == null) {
// No callbacks to execute, return early.
return;
}
log("Resolving callbacks");
// ...
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(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);
}
}
}
这个方法内部会调用executeCallbacks,由于之前未给ClientTransaction添加callbacks,所以,这个方法内部未执行任何的回调。下面接着看executeLifecycleState(transaction);方法
private void executeLifecycleState(ClientTransaction transaction) {
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
if (lifecycleItem == null) {
return;
}
final IBinder token = transaction.getActivityToken();
final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
if (r == null) {
return;
}
// Cycle to the state right before the final requested state.
cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);
// Execute the final transition with proper parameters.
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}
private void cycleToPath(ActivityClientRecord r, int finish,
boolean excludeLastState) {
//此时Launcher的状态是onResume,所以start为3
final int start = r.getLifecycleState();
log("Cycle from: " + start + " to: " + finish + " excludeLastState:" + excludeLastState);
final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
performLifecycleSequence(r, path);
}
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);
}
}
}
这个方法内部,会执行cycleToPath方法,这个方法的主要作用是,根据传入的targetState状态,和当前的状态,计算出是否存中间状态,如果存在,则将中间状态和传入的状态生命周期的方法按照顺序执行。
打个比方:加入目前的Activity是处于onResume状态的,则lifecycleItem就是ResumeActivityItem类型的,通过lifecycleItem.getTargetState()获取的就是对应的一个状态常量,这个常量就是3,
在ActivityLifecycleItem这个类中,有如下这些状态常量:
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;
public static final int ON_RESTART = 7;
由于这里假设当前状态是onResume状态,所以,cycleToPath方法内部的start的值就是3,finish的值,是4,为什么是4呢?因为executeLifecycleState方法中的,lifecycleItem其实就是PauseActivityItem,所以PauseActivityItem对象获取的targetState的值就是4,这样,通过cycleToPath方法计算的发现,他们中间并未存在中间状态,所以,通过mHelper.getLifecyclePath方法获取的IntArray的值是0,下面看看getLifecyclePath方法
的具体实现:
http://androidxref.com/9.0.0_r3/xref/frameworks/base/core/java/android/app/servertransaction/TransactionExecutorHelper.java
@VisibleForTesting
public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) {
// ...
mLifecycleSequence.clear();
// finish = 4 start = 3,
if (finish >= start) {
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) {
// Special case when we can just directly go to resumed state.
mLifecycleSequence.add(ON_RESUME);
} else if (start <= ON_STOP && finish >= ON_START) {
// Restart and go to required state.
// Go to stopped state first.
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 {
// Relaunch and go to required state
// Go to destroyed state first.
for (int i = start + 1; i <= ON_DESTROY; i++) {
mLifecycleSequence.add(i);
}
// Go to required state
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;
}
通过这个方法,可以看出,如果finish是4,start是3,则这个方法最后返回的mLifecycleSequence的size是0,所以cycleToPath方法其实什么都没做。下面继续看executeLifecycleState()方法的具体实现:
private void executeLifecycleState(ClientTransaction transaction) {
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
if (lifecycleItem == null) {
return;
}
final IBinder token = transaction.getActivityToken();
final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
if (r == null) {
return;
}
// ...
cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}
分析完这个方法内部的cycleToPath方法后,继续看lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
这行代码,由于之前分析过ClientLifecycleManager类的transactionWithState方法,所以,这个lifecycleItem其实就是PauseActivityItem类的execute方法,下面看看这个方法的具体实现:
http://androidxref.com/9.0.0_r3/xref/frameworks/base/core/java/android/app/servertransaction/PauseActivityItem.java
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions,
"PAUSE_ACTIVITY_ITEM");
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
这个方法中的client正好是ClientTransactionHandler,由于ClinetTransactionHandler是个抽象类,所以执行这个方法的是其子类ActivityThread的handlePauseActivity方法,下面看看ActivityThread类的handlePauseActivity方法的具体实现:
http://androidxref.com/9.0.0_r3/xref/frameworks/base/core/java/android/app/ActivityThread.java
@Override
public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
int configChanges, PendingTransactionActions pendingActions, String reason) {
ActivityClientRecord r = mActivities.get(token);
if (r != null) {
if (userLeaving) {
performUserLeavingActivity(r);
}
r.activity.mConfigChangeFlags |= configChanges;
// 关键代码
performPauseActivity(r, finished, reason, pendingActions);
// Make sure any pending writes are now committed.
if (r.isPreHoneycomb()) {
QueuedWork.waitToFinish();
}
mSomeActivitiesChanged = true;
}
}
private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
PendingTransactionActions pendingActions) {
// ...
// 关键代码
performPauseActivityIfNeeded(r, reason);
ArrayList listeners;
synchronized (mOnPauseListeners) {
listeners = mOnPauseListeners.remove(r.activity);
}
int size = (listeners != null ? listeners.size() : 0);
for (int i = 0; i < size; i++) {
listeners.get(i).onPaused(r.activity);
}
final Bundle oldState = pendingActions != null ? pendingActions.getOldState() : null;
if (oldState != null) {
if (r.isPreHoneycomb()) {
r.state = oldState;
}
}
return shouldSaveState ? r.state : null;
}
private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
// ...
try {
r.activity.mCalled = false;
//关键代码
mInstrumentation.callActivityOnPause(r.activity);
if (!r.activity.mCalled) {
throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)
+ " did not call through to super.onPause()");
}
}
// ...
r.setState(ON_PAUSE);
}
上面对performPauseActivityIfNeed方法中,执行了Instrumentation的callActivityOnPause方法,下面看看这个方法的具体实现:
http://androidxref.com/9.0.0_r3/xref/art/test/Instrumentation/Instrumentation.java
public void callActivityOnPause(Activity activity) {
activity.performPause();
}
这个方法内部最终调用了Activity的performPause方法,接着调用OnPause方法,这样Activity的OnPause方法就执行了。
以上就是Activity的onPasue方法的执行过程分析。