如何回到App进程
上一篇文章中说道:IApplicationThread类型的实例会跨进程调用schedulePauseActivity,让App中的MainActivity pause掉。
IApplicationThread是如何跨进程的呢?
回顾第一篇文章中,MainActivity调用startActivity通知AMS的时候,会传入一个caller:android.app.ActivityThread.ApplicationThread对象,它实现了IApplicationThread,又是一个Binder对象,支持跨进程调用。因此AMS拿它来通知App进程做一些事情。
caller是调用MainActivity的android.app.Activity#mMainThread属性的getApplicationThread函数获得的。android.app.Activity#mMainThread是android.app.ActivityThread类型。
再看一下android.app.ActivityThread#getApplicationThread:
final ApplicationThread mAppThread = new ApplicationThread();
...
public ApplicationThread getApplicationThread()
{
return mAppThread;
}
...
ApplicationThread和ActivityThread一一对应。一个ActivityThread又和一个App进程一一对应。因此可以理解为一个ApplicationThread代表一个App进程,AMS就是使用它回到App进程的。
通知Activity执行pause
android.app.ActivityThread.ApplicationThread#schedulePauseActivity:
public final void schedulePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges) {
queueOrSendMessage(
finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
token,
(userLeaving ? 1 : 0),
configChanges);
}
传入的三个参数:
- token:最重要的一个参数,稍后详细分析
- finished:表示Activity是否被finish了,这里传入false
- userLeaving:用户是否离开界面,场景无关
- configChanges:场景无关
token是ActivityRecord创建的时候实例化的,前面的文章中见过ActivityRecord的实例化,但是它是TargetActivity的实例化。同样MainActivity在启动的时候一样有它的ActivityRecord的实例化。
com.android.server.am.ActivityRecord::
...
static class Token extends IApplicationToken.Stub {
final WeakReference<ActivityRecord> weakActivity;
Token(ActivityRecord activity) {
weakActivity = new WeakReference<ActivityRecord>(activity);
}
...
ActivityRecord(...){
...
appToken = new Token(this);
...
}
...
IApplicationToken.Stub继承了IApplicationToken.Stub接口。因此这里的Token可以和ActivityRecord一一对应,它代表了AMS中一条Activity记录。
回到schedulePauseActivity中继续分析android.app.ActivityThread#queueOrSendMessage(int, java.lang.Object, int, int):
private void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
synchronized (this) {
if (DEBUG_MESSAGES) Slog.v(
TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
+ ": " + arg1 + " / " + obj);
Message msg = Message.obtain();
msg.what = what;
msg.obj = obj;
msg.arg1 = arg1;
msg.arg2 = arg2;
mH.sendMessage(msg);
}
}
代码比较简单,给App的UI进程looper发送一个消息。
Activity处理pause消息
其中android.app.ActivityThread#mH:
...
final H mH = new H();
...
private class H extends Handler {
...
public static final int PAUSE_ACTIVITY = 101;
...
public void handleMessage(Message msg) {
switch (msg.what) {
...
// 走到这个case
case PAUSE_ACTIVITY:
...
handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
...
break;
...
private void handlePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges) {
ActivityClientRecord r = mActivities.get(token);
if (r != null)
//涉及到Activity中的onUserInteraction、onUserLeaveHint调用,这里不再分析
if (userLeaving) {
performUserLeavingActivity(r);
}
//场景无关
r.activity.mConfigChangeFlags |= configChanges;
//执行pause的地方
performPauseActivity(token, finished, r.isPreHoneycomb());
// 一些兼容性处理,场景无关
if (r.isPreHoneycomb()) {
QueuedWork.waitToFinish();
}
// 告诉AMS已经pause掉了
try {
ActivityManagerNative.getDefault().activityPaused(token);
} catch (RemoteException ex) {
}
}
}
主要做了两件事:
- 调用MainActivity的onPause
- 告诉AMS已经pause完了
继续分析android.app.ActivityThread#performPauseActivity(android.os.IBinder, boolean, boolean):
...
final HashMap<IBinder, ActivityClientRecord> mActivities
= new HashMap<IBinder, ActivityClientRecord>();
...
final Bundle performPauseActivity(IBinder token, boolean finished,
boolean saveState) {
ActivityClientRecord r = mActivities.get(token);
return r != null ? performPauseActivity(r, finished, saveState) : null;
}
mHistory是系统侧Activity记录的地方,相对应的mActivities是App进程侧记录Activity的地方。ActivityClientRecord和ActivityRecord一一对应。从mActivities取到MainActivity对应的ActivityClientRecord,而存ActivityClientRecord是在MainActivity启动时做过的。继续调用android.app.ActivityThread#performPauseActivity(android.app.ActivityThread.ActivityClientRecord, boolean, boolean):
final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
boolean saveState) {
//已经pause掉了且finish了,直接return,不走这
if (r.paused) {
if (r.activity.mFinished) {
return null;
}
//直接抛异常
RuntimeException e = new RuntimeException(
"Performing pause of activity that is not resumed: "
+ r.intent.getComponent().toShortString());
Slog.e(TAG, e.getMessage(), e);
}
Bundle state = null;
//不走这
if (finished) {
r.activity.mFinished = true;
}
try {
//这里会调用Activity的onSaveInstanceState,不走这
if (!r.activity.mFinished && saveState) {
...
}
// 为了记录状态的,表示pause还没被调用
r.activity.mCalled = false;
// 调用Activity的onPause,把r.activity.mCalled设置成true
mInstrumentation.callActivityOnPause(r.activity);
EventLog.writeEvent(LOG_ON_PAUSE_CALLED, r.activity.getComponentName().getClassName());
//pause没有调用成功,直接抛异常
if (!r.activity.mCalled) {
throw new SuperNotCalledException(
"Activity " + r.intent.getComponent().toShortString() +
" did not call through to super.onPause()");
}
} catch (SuperNotCalledException e) {
throw e;
} catch (Exception e) {
if (!mInstrumentation.onException(r.activity, e)) {
throw new RuntimeException(
"Unable to pause activity "
+ r.intent.getComponent().toShortString()
+ ": " + e.toString(), e);
}
}
r.paused = true;
...
return state;
}
继续分析android.app.Instrumentation#callActivityOnPause:
public void callActivityOnPause(Activity activity) {
activity.performPause();
}
final void performPause() {
//如果有fragment,给它们分发一下pause调用
mFragments.dispatchPause();
//再次记录onPause还没被调用
mCalled = false;
//生命周期onPause的调用,会把mCalled设置成true
onPause();
mResumed = false;
//重写onPause时没有调用super.onPause,导致mCalled还是false,targetSdkVersion>=9的话,直接抛异常。
if (!mCalled && getApplicationInfo().targetSdkVersion
>= android.os.Build.VERSION_CODES.GINGERBREAD) {
throw new SuperNotCalledException(
"Activity " + mComponent.toShortString() +
" did not call through to super.onPause()");
}
//为啥设置两次?没看明白
mResumed = false;
}
protected void onPause() {
if (DEBUG_LIFECYCLE) Slog.v(TAG, "onPause " + this);
//一些pause的回调监听处理
getApplication().dispatchActivityPaused(this);
mCalled = true;
}
不出意外,onPause设置mCalled为true。
这样MainActivity的pause就真正完成了,但是AMS还没有把TargetActivity启动起来呢。这时就需要回到AMS系统进程中,继续完成剩余任务了,它是由:ActivityManagerNative.getDefault().activityPaused(token);完成的。
总结
App进程侧的pause操作,包含三个过程:
- 通过向App主线程looper发消息,告知它调用指定Activity的onPause
- Activity收到消息,执行onPause
- App进程告知AMS:已经完成pause操作
最后AMS收到“完成pause”的消息后,肯定会继续完成启动TargetActivity的剩余任务,由此第三次握手就开始了。