我们从startActivity开始讲解。
1.Activity::startActivity
public void startActivity(Intent intent) {
this.startActivity(intent, null);
}
public void startActivity(Intent intent, @Nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
// Note we want to go through this call for compatibility with
// applications that may have overridden the method.
startActivityForResult(intent, -1);
}
}
2.Activity::startActivityForResult
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
startActivityForResult(intent, requestCode, null);
}
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) {
if (mParent == null) {
options = transferSpringboardActivityOptions(options);
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult(
mToken, mEmbeddedID, requestCode, ar.getResultCode(),
ar.getResultData());
}
//上面出来的为-1
if (requestCode >= 0) {
// If this start is requesting a result, we can avoid making
// the activity visible until the result is received. Setting
// this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
// activity hidden during this time, to avoid flickering.
// This can only be done when a result is requested because
// that guarantees we will get information back when the
// activity is finished, no matter what happens to it.
mStartedActivity = true;
}
cancelInputsAndStartExitTransition(options);
// TODO Consider clearing/flushing other event sources and events for child windows.
} else {
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
// Note we want to go through this method for compatibility with
// existing applications that may have overridden it.
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}
- Instrumentation::execStartActivity
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
......省略
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(who);
int result =ActivityManager.getServeice .startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
在8.0之前上面代码是ActivityManagerNative.getDefault().startActivity(),8.0之后与AMS与ActivityManger的binder通信采用了AIDL的方式,在我的另一个文档讲解AMS成员的时候提到了这块代码变化,现在我们来看AMS中的startActivity。
4.ActivityManagerService::startActivity
public final int startActivity(IApplicationThread caller, String callingPackage,Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}
//P版新增。
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) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
true /*validateIncomingUser*/);
}
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");
// TODO: Switch to user app stacks here.
//在P版之前调用的是mActivityStarter.startActivityMayWait
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();
}
9.0这一块代码比较之前有了一个很大变化,第一眼我看的时候一脸蒙蔽,只看到后面执行了execute(),但是没看到在哪里执行,我们一步步来。
5.ActivityStartController::obtainStarter
ActivityStarter obtainStarter(Intent intent, String reason) {
return mFactory.obtain().setIntent(intent).setReason(reason);
}
然后看看这个mFactory的定义,这个类中全局搜索了一下,发现 Factory mFactory,在搜索一下Factory,看看是哪个类的工厂模式,我们看到导的包中:
import com.android.server.am.ActivityStarter.Factory;
来到ActivityStarter.java这个类
interface Factory {
void setController(ActivityStartController controller);
ActivityStarter obtain();
void recycle(ActivityStarter starter);
}
找找实现类,在下面就有。
static class DefaultFactory implements Factory {
@Override
public ActivityStarter obtain() {
ActivityStarter starter = mStarterPool.acquire();
if (starter == null) {
starter = new ActivityStarter(mController, mService, mSupervisor, mInterceptor);
}
return starter;
}
}
最终返回的是ActivityStarter的实例。
看看setIntent。
ActivityStarter setIntent(Intent intent) {
mRequest.intent = intent;
return this;
}
我们可以看出这个方法只要是为了给mRequest赋值,然后返回
同理:
ActivityStarter setReason(String reason) {
mRequest.reason = reason;
return this;
}
ActivityStarter setCaller(IApplicationThread caller) {
mRequest.caller = caller;
return this;
}
.......
ActivityStarter setMayWait(int userId) {
mRequest.mayWait = true;
mRequest.userId = userId;
return this;
}
我们可以看到mActivityStartController.obtainStarter后面那一段方法,全是这样。
然后我们再看看execute();
int execute() {
try {
// TODO(b/64750076): Look into passing request directly to these methods to allow
// for transactional diffs and preprocessing.
if (mRequest.mayWait) {
return startActivityMayWait(mRequest.caller, mRequest.callingUid,mRequest.callingPackage, mRequest.intentmRequest.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,而在9.0之前不需要这么麻烦,直接在上面那一步调这个函数。
6.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) {
.....省略了pkms解析intent的代码
synchronized (mService) {
.....省略
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);
....省略
}
}
7.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) {
......省略
mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
options, ignoreTargetSecurity, componentSpecified,
mLastStartActivityRecord,
inTask, allowPendingRemoteAnimationRegistryLookup);
.....省略
}
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, boolean allowPendingRemoteAnimationRegistryLookup) {
......省略//检查启动Activity的权限。创建ActivityRecord等等
return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
true /* doResume */, checkedOptions, inTask, outActivity);
}
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();
result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, outActivity);
} finally {
......省略
}
postStartActivityProcessing(r, result, mTargetStack);
return result;
}
- ActivityStarter::startActivityUnchecked
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
//1.
setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
voiceInteractor);computeLaunchingTaskFlags();
//2.
computeLaunchingTaskFlags();
....省略若干行
//根据应用的启动模式设置栈
if (mStartActivity.getTask() == null && !clearTopAndResetStandardLaunchMode) {
mStartActivity.setTask(reusedActivity.getTask());
}
.....省略若干行
//3.
mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,mOptions);
......
mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,mOptions);
......
}
注释1处用于初始化启动Activity的各种配置,在初始化前会重置各种配置再进行配置,这些配置包括:ActivityRecord、Intent、TaskRecord和LaunchFlags(启动的FLAG)等等。
注释2处的computeLaunchingTaskFlags方法用于计算出启动的FLAG,并将计算的值赋值给mLaunchFlags。
注释3这个代码的作用就是将处理好的task相关参数,传递给WindowManager为task的切换.
接下来我们看看resumeFocusedStackTopActivityLocked();这个类在ActivityStackSupervisor.java中
- ActivityStackSupervisor::resumeFocusedStackTopActivityLocked()
boolean resumeFocusedStackTopActivityLocked(ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
......
if (targetStack != null && isFocusedStack(targetStack)) {
return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
.....
if (r == null || !r.isState(RESUMED)) {
mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
}
}
接下来我们看看ActivityStack.java中的resumeTopActivityUncheckedLocked()。
- ActivityStack::resumeTopActivityUncheckedLocked
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;
result = resumeTopActivityInnerLocked(prev, options);
final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
if (next == null || !next.canTurnScreenOn()) {
checkReadyForSleep();
}
} finally {
mStackSupervisor.inResumeTopActivity = false;
}
return result;
}
11.ActivityStack::resumeTopActivityInnerLocked
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
//这个方法很庞大,
....
mStackSupervisor.startSpecificActivityLocked(next, true, true)
....
}
现在又回调到了ActivityStackSupervisor.startSpecificActivityLocked();
12.ActivityStackSupervisor::startSpecificActivityLocked
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
...
//如果这个app已经被启动。
if (app != null && app.thread != null) {
...
realStartActivityLocked(r, app, andResume, checkConfig);
...
}
//app没有启动,执行下面的。本文不讲,后面单独讲
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);
}
13.ActivityStackSupervisor::realStartActivityLocked
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
......
try{
.....
// Create activity launch transaction.
final ClientTransaction clientTransaction = ClientTransaction.**obtain**(app.thread,r.appToken);
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));
.........
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
.......
} finally {
endDeferResume();
}
........
}
这块代码有何之前不一样,我们可以看出9.0我们是开启了一个事务机制,先看看8.0之前怎么做的。
ActivityInfo resolveActivity(Intent intent, ResolveInfo rInfo, int startFlags,
ProfilerInfo profilerInfo) {
......
try{
.....
app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,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, !andResume,
mService.isNextTransitionForward(), profilerInfo);
.....
}
我们可以看出在9.0之前的老代码中,我们调用了app.thread.scheduleLaunchActivity();
这是9.0做出的一下改变,不过没关系,我们继续看看scheduleTransaction()。
我们先看看AMS中的getLifecycleManager().
AMS::getLifecycleManager()
ClientLifecycleManager getLifecycleManager() {
return mLifecycleManager;
}
说明我们scheduleTransaction()是在ClientLifecycleManager.java中调用,继续往下看。
ClientLifecycleManager::scheduleTransaction
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.java中的schedule()。
ClientTransaction::schedule()
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
全局一下mClient,发现是 private IApplicationThread mClient,然后我们找一下IApplicationThread的实现类ApplicationThread,他是ActivityThread中的一个内部类
ActivityThread->ApplicationThread::scheduleTransaction
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
全局了一下scheduleTransaction,可是ActivityThread这个内本身并没有定义这个函数,难道我们分析就在此处断了?
现在我们看看ActivityThread的继承关系,我们看到ActivityThread extends ClientTransactionHandler,那我们去父类找找。
ClientTransactionHandler::scheduleTransaction
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
我们看到这个函数给ActivityThread中的内部类H发送了一个消息,看看这个H中的HandleMessage(),看看对EXECUTE_TRANSACTION的处理。
ActivityThread->H::HandleMessage()
public void handleMessage(Message msg) {
.....
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;
.....
}
mTransactionExecutor全局搜索,看到了TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
那我们找找TransactionExecutor中的execute();
TransactionExecutor::execute
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
TransactionExecutor::executeCallbacks
public void executeCallbacks(ClientTransaction transaction) {
.....
for (int i = 0; i < size; ++i) {
final ClientTransactionItem item = callbacks.get(i);
.....
item.execute(mTransactionHandler, token, mPendingActions);
}
}
不多说看看ClientTransactionItem.java,可是这个类是个抽象类。
public abstract class ClientTransactionItem implements BaseClientRequest, Parcelable {
......
}
还是找实现类。
最开始我在整个framework下全局搜了一下,发现有好几个类都继承了ClientTransactionItem,
最后当我看到LaunchActivityItem.java,感觉很眼熟,似乎在哪里见过,原来在我们ActivityStackSupervisor::realStartActivityLocked中我们clientTransaction.addCallback()时我们传入的就是ClientTransactionItem类型的参数。
clientTransaction::addCallback
public void addCallback(ClientTransactionItem activityCallback) {
if (mActivityCallbacks == null) {
mActivityCallbacks = new ArrayList<>();
}
mActivityCallbacks.add(activityCallback);
}
可以看到LaunchActivityItem.obtain(new Intent(r.intent),来到LaunchActivityItem.java
14.LaunchActivityItem::execute
public 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.handleLaunchActivity(r, pendingActions, null /* customIntent */);
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
感觉终于找到我们找到的了,看execute的参数,client是ClientTransactionHandler类型,我们前面说了这个ClientTransactionHandler是个抽象类,他的实现类是ActivityThread.
直接去ActivityThread下搜索。
15.ActivityThread::handleLaunchActivity
public Activity handleLaunchActivity(ActivityClientRecord r,PendingTransactionActions pendingActions, Intent customIntent) {
........
final Activity a = **performLaunchActivity**(r, customIntent);
........
}
16.ActivityThread::performLaunchActivity
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
.....
if (r.isPersistable()) {
mInstrumentation.**callActivityOnCreate**(activity, r.state, r.persistentState);
} else {
mInstrumentation.**callActivityOnCreate**(activity, r.state);
}
....
}
可以看到又回到了Instrumentation中。
17.Instrumentation::callActivityOnCreate
public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);
activity.performCreate(icicle);
postPerformCreate(activity);
}
public void callActivityOnCreate(Activity activity, Bundle icicle,
PersistableBundle persistentState) {
prePerformCreate(activity);
activity.performCreate(icicle, persistentState);
postPerformCreate(activity);
}
我们看到最终有回到了Activity.java中调用performCreate();
18.Activity::performCreate
final void performCreate(Bundle icicle) {
performCreate(icicle, null);
}
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
mCanEnterPictureInPicture = true;
restoreHasCurrentPermissionRequest(icicle);
if (persistentState != null) {
onCreate(icicle, persistentState);
} else {
onCreate(icicle);
}
writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate");
mActivityTransitionState.readState(icicle);
mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
com.android.internal.R.styleable.Window_windowNoDisplay, false);
mFragments.dispatchActivityCreated();
mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
}
最终我们可以看到Activity.onCreate()被调用,activity启动了。
网友评论