我们常用的startActivity
方法
@Override
public void startActivity(Intent intent) {
this.startActivity(intent, null);
}
调用了带Bundler
参数的重载方法
@Override
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);
}
}
最终会调用了startActivityForResult
方法,也就是说我们平常调用的所有重载startAcitvity
其实就是调用startAcitivityForResult
,只不过requesetCode
参数为-1
startAcitivityForResult
里面调用了Instrumentation
类的execStartActivity
方法,Instrumentation
这个类很重要,我们和四大组件打交道方法基本都是调用的这个类的方法,那这个对象什么时候给赋值的呢?
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);
...省略部分代码
}
}
在attach
方法里面我们看到是系统创建好直接传递进来的,也就是说这个对象是外面创建好的,至于哪里创建好的,那要涉及到app
的启动流程了,后面再讲。这里我们先知道,一个app
的这个类只有一个实例对象。
可以看到attach
方法里面传递了很多已经创建好的重要的对象,比如我们的application
对象
final void attach(Context context, ActivityThread aThread,
Instrumentation instr, IBinder token, int ident,
Application application, Intent intent, ActivityInfo info,
CharSequence title, Activity parent, String id,
NonConfigurationInstances lastNonConfigurationInstances,
Configuration config, String referrer, IVoiceInteractor voiceInteractor,
Window window) {
attachBaseContext(context);
mFragments.attachHost(null /*parent*/);
mWindow = new PhoneWindow(this, window);
mUiThread = Thread.currentThread();
mInstrumentation = instr;
mToken = token;
....
}
继续追踪Instrumentation
里面的execStartActivity
方法
可以看到里面调用了ActivityManagerNative.getDefault().startActivity
方法。通过这个调用,我们大概可以猜到这个调用是获取单例,继续去看ActivityManagerNative
类
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 = ActivityManagerNative.getDefault()
.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;
}
发现这个ActivityManagerNative
继承了Binder
,而Binder
是干嘛用的,Binder
实现了IBinder
接口,IBinder
我们应该不陌生,在AIDL
,绑定服务的时候,返回给调用的就是一个IBinder
实现对象。这里其实就是返回了系统的ActivityManagerService
的一个Binder
代理对象,
public abstract class ActivityManagerNative extends Binder implements IActivityManager
static public IActivityManager getDefault() {
return gDefault.get();
}
//gDefult对象的创建,就是一个单例,
private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
protected IActivityManager create() {
IBinder b = ServiceManager.getService("activity");
if (false) {
Log.v("ActivityManager", "default service binder = " + b);
}
IActivityManager am = asInterface(b);
if (false) {
Log.v("ActivityManager", "default service = " + am);
}
return am;
}
};
查看SingleTon
就知道get()
方法返回的就是create()
方法创建的对象
public abstract class Singleton<T> {
private T mInstance;
protected abstract T create();
public final T get() {
synchronized (this) {
if (mInstance == null) {
mInstance = create();
}
return mInstance;
}
}
}
这个时候当前调用线程挂起,代码就跑到到系统进程来了,查看ActivityManagerService
的startActivity
方法
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback
@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
Intent intent, ...省略参数) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}
}
内部调用了startAcitivityAsUser
方法
@Override
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, ...省略参数) {
enforceNotIsolatedCaller("startActivity");
userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
userId, false, ALLOW_FULL_ONLY, "startActivity", null);
//调用ActivityStarter的startAcitivityMayWait方法
return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
profilerInfo, null, null, bOptions, false, userId, null, null);
}
这里调用了ActivityStarter
的startAcitivityMayWait
方法,这个方法比较长,下面是分析一些关键的代码,可以看到ResolverInfo
对象和AcitivityInfo
对象这个时候开始创建了。这个ActivityInfo
就是对应着调用者APP里面的Activity
,同样,四大组件在系统服务这边都有着这样的对应关系。
final int startActivityMayWait(省略很长很长的参数) {
//生成ResolverInfo对象
ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId);
// 生成AcitivityInfo对象
ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
final ActivityRecord[] outRecord = new ActivityRecord[1];
//调用startAcitivityLocked方法
int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType,
aInfo, rInfo, voiceSession, voiceInteractor,
resultTo, resultWho, requestCode, callingPid,
callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
options, ignoreTargetSecurity, componentSpecified, outRecord, container,
inTask);
return res;
}
}
调用startAcitivityLocked
方法,这个方法依然很长啊,前面一大段代码是检查工作,继续挑重点的看,调用了startAcitivityUnchecked
final int startActivityLocked() {
int err = ActivityManager.START_SUCCESS;
try {
mService.mWindowManager.deferSurfaceLayout();
err = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
true, options, inTask);
} finally {
mService.mWindowManager.continueSurfaceLayout();
}
postStartActivityUncheckedProcessing(r, err, stack.mStackId, mSourceRecord, mTargetStack);
return err;
}
startAcitivityUnchecked
方法,依然看重点
这个调用了ActivityStack
的startAcitivityLocaked
方法
private int startActivityUnchecked(省略参数) {
//省略前面代码
mTargetStack.startActivityLocked(mStartActivity, newTask, mKeepCurTransition, mOptions);
return START_SUCCESS;
}
通过这个ActivityStack
类名我们大概可以猜测这个类应该是操作acitivity
栈的,因为我们都知道每个app都有一个或者多个acitivity
栈,开启一个acitivity
都需要入栈退出的acitivity
都需要出栈,这些都是系统内部处理的。
进入AcitivityStack
类的startAcitityLocaked
方法,可以看到startActivityLocked
方法里面把当前activity
放到了栈顶,并且当前activity
所处的栈设置为前台栈
final void startActivityLocked(ActivityRecord r, boolean newTask, boolean keepCurTransition,
ActivityOptions options) {
TaskRecord task = null;
//把当前activity设置到栈顶
task.addActivityToTop(r);
//把栈设置前台栈
task.setFrontOfTask();
if (VALIDATE_TOKENS) {
validateAppTokensLocked();
}
}
调用完成后再回到AcitivityStarter
的startAcitivityUnchecked
private int startActivityUnchecked(省略参数) {
mTargetStack.startActivityLocked(mStartActivity, newTask, mKeepCurTransition, mOptions);
mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
mOptions);
}
}
前面的startActivityLocked
调用完成后,再调用
AcitivityStackSupervisor
的resumeFocusedStackTopActivityLocked
方法
boolean resumeFocusedStackTopActivityLocked(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
if (targetStack != null && isFocusedStack(targetStack)) {
return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
if (r == null || r.state != RESUMED) {
mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
}
return false;
}
又调用AcitivityStarter
的resumeTopActivityUncheckedLocked
方法
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
boolean result = false;
try {
// Protect against recursion.
mStackSupervisor.inResumeTopActivity = true;
if (mService.mLockScreenShown == ActivityManagerService.LOCK_SCREEN_LEAVING) {
mService.mLockScreenShown = ActivityManagerService.LOCK_SCREEN_HIDDEN;
mService.updateSleepIfNeededLocked();
}
result = resumeTopActivityInnerLocked(prev, options);
} finally {
mStackSupervisor.inResumeTopActivity = false;
}
return result;
}
又调用了resumeTopActivityInnerLocked
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
// 获取当前正在栈顶的Activity信息
final ActivityRecord next = topRunningActivityLocked();
final TaskRecord prevTask = prev != null ? prev.task : null;
next.delayedResume = false;
if (mResumedActivity != null) {
pausing |= startPausingLocked(userLeaving, false, next, dontWaitForPause);
return true;
}
继续调用了startPausingLocked
,传入的这个next
参数就是当前栈顶的activity
信息,看方法名称我们大概知道应该会走acitivity onPause
方法回调了。
继续看startPausingLocked
方法
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
ActivityRecord resuming, boolean dontWait) {
ActivityRecord prev = mResumedActivity;
try {
//thread 即IApplicationThread
prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
userLeaving, prev.configChangeFlags, dontWait);
} catch (Exception e) {
// Ignore exception, if process died other code will cleanup.
Slog.w(TAG, "Exception thrown during pause", e);
mPausingActivity = null;
mLastPausedActivity = null;
mLastNoHistoryActivity = null;
}
}
if (dontWait) {
// If the caller said they don't want to wait for the pause, then complete
// the pause now.
completePauseLocked(false, resuming);
return false;
} else {
Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
msg.obj = prev;
prev.pauseTime = SystemClock.uptimeMillis();
mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Waiting for pause to complete...");
return true;
}
} else {
if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Activity not running, resuming next.");
if (resuming == null) {
mStackSupervisor.resumeFocusedStackTopActivityLocked();
}
return false;
}
}
这个IApplicationThread
的实现就是ActivityThread
内部类ApplicationThread
,这个类继承了ApplicationThreadNative
,ApplicationThreadNative
又继承了Binder
,因此系统可以和我们的APP通讯。
上面是在系统进程里面执行的,但最终还是要回到我们自己的APP进程啊,这个时候系统持有我们APP 的一个Binder
,和我们和系统进程通讯是一样的
public abstract class ApplicationThreadNative extends Binder
implements IApplicationThread
//这个类是ActivityThread的内部类
//这个时候回到我们自己的APP进程了。
private class ApplicationThread extends ApplicationThreadNative {
private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
private int mLastProcessState = -1;
public final void schedulePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges, boolean dontReport) {
int seq = getLifecycleSeq();
if (DEBUG_ORDER) Slog.d(TAG, "pauseActivity " + ActivityThread.this
+ " operation received seq: " + seq);
sendMessage(
finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
token,
(userLeaving ? USER_LEAVING : 0) | (dontReport ? DONT_REPORT : 0),
configChanges,
seq);
}
private void sendMessage(int what, Object obj, int arg1, int arg2, int seq) {
Message msg = Message.obtain();
msg.what = what;
SomeArgs args = SomeArgs.obtain();
args.arg1 = obj;
args.argi1 = arg1;
args.argi2 = arg2;
args.argi3 = seq;
msg.obj = args;
mH.sendMessage(msg);
}
final H mH = new H();
内部有个Handler
。通过这个Handler发送了一个PAUSE_ACTIVITY
消息
private class H extends Handler
//找到处理PAUSE_ACTIVITY消息的地方
case PAUSE_ACTIVITY: {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
SomeArgs args = (SomeArgs) msg.obj;
handlePauseActivity((IBinder) args.arg1, false,
(args.argi1 & USER_LEAVING) != 0, args.argi2,
(args.argi1 & DONT_REPORT) != 0, args.argi3);
maybeSnapshot();
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;
继续查看handlePauseActivity
方法,
private void handlePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges, boolean dontReport, int seq) {
performPauseActivity(token, finished, r.isPreHoneycomb(), "handlePauseActivity");
// Tell the activity manager we have paused.
if (!dontReport) {
try {
//回调给系统ActivityManagerService
ActivityManagerNative.getDefault().activityPaused(token);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
mSomeActivitiesChanged = true;
}
}
调用了performPauseActivity
final Bundle performPauseActivity(IBinder token, boolean finished,
boolean saveState, String reason) {
ActivityClientRecord r = mActivities.get(token);
return r != null ? performPauseActivity(r, finished, saveState, reason) : null;
}
performPauseActivity
调用重载方法
final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
boolean saveState, String reason) {
performPauseActivityIfNeeded(r, reason);
return !r.activity.mFinished && saveState ? r.state : null;
}
调用了performPauseActivityIfNeeded
方法
private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
try {
r.activity.mCalled = false;
mInstrumentation.callActivityOnPause(r.activity);
EventLog.writeEvent(LOG_AM_ON_PAUSE_CALLED, UserHandle.myUserId(),
r.activity.getComponentName().getClassName(), reason);
if (!r.activity.mCalled) {
throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)
+ " 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 "
+ safeToComponentShortString(r.intent) + ": " + e.toString(), e);
}
}
r.paused = true;
}
调用了Instrumentation
内的callAcitivityOnPause
方法。终于调用到了Acitivity
的方法。
public void callActivityOnPause(Activity activity) {
activity.performPause();
}
Activity
的performPause
方法。看到了熟悉的onPause
生命周期方法。看到没有,如果我们没有调用super.onPause()
方法,则会报异常。
final void performPause() {
mDoReportFullyDrawn = false;
mFragments.dispatchPause();
mCalled = false;
onPause();
mResumed = false;
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;
}
分析到这终于看到调用我们自己的代码了。
真是漫漫长路。喝杯水先.........继续往下分析。
前面才是当前Acitivity
调用了onPause()
方法,要开启的acitivity
的生命周期在哪里被调用的呢?
继续回到handlePauseAcitivity
方法,这个时候又通过Binder
调用ActivityManagerSer
的方法
private void handlePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges, boolean dontReport, int seq) {
// Tell the activity manager we have paused.
if (!dontReport) {
try {
//回调给系统ActivityManagerService
ActivityManagerNative.getDefault().activityPaused(token);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
mSomeActivitiesChanged = true;
}
}
继续到系统进程
ActivityManagerService
里面的acitivityPaused
方法
@Override
public final void activityPaused(IBinder token) {
final long origId = Binder.clearCallingIdentity();
synchronized(this) {
ActivityStack stack = ActivityRecord.getStackLocked(token);
if (stack != null) {
stack.activityPausedLocked(token, false);
}
}
Binder.restoreCallingIdentity(origId);
}
调用ActivityStack
的activityPausedLocked
方法
final void activityPausedLocked(IBinder token, boolean timeout) {
if (DEBUG_PAUSE) Slog.v(TAG_PAUSE,
"Activity paused: token=" + token + ", timeout=" + timeout);
final ActivityRecord r = isInStackLocked(token);
if (r != null) {
mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
if (mPausingActivity == r) {
if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to PAUSED: " + r
+ (timeout ? " (due to timeout)" : " (pause complete)"));
completePauseLocked(true, null);
return;
} else {
}
}
mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
}
调用completePauseLocked
方法
private void completePauseLocked(boolean resumeNext, ActivityRecord resuming) {
ActivityRecord prev = mPausingActivity;
if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Complete pause: " + prev);
if (resumeNext) {
final ActivityStack topStack = mStackSupervisor.getFocusedStack();
if (!mService.isSleepingOrShuttingDownLocked()) {
mStackSupervisor.resumeFocusedStackTopActivityLocked(topStack, prev, null);
} else {
mStackSupervisor.checkReadyForSleepLocked();
ActivityRecord top = topStack.topRunningActivityLocked();
if (top == null || (prev != null && top != prev)) {
mStackSupervisor.resumeFocusedStackTopActivityLocked();
}
}
}
if (prev != null) {
prev.resumeKeyDispatchingLocked();
if (prev.app != null && prev.cpuTimeAtResume > 0
&& mService.mBatteryStatsService.isOnBattery()) {
long diff = mService.mProcessCpuTracker.getCpuTimeForPid(prev.app.pid)
- prev.cpuTimeAtResume;
if (diff > 0) {
BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
synchronized (bsi) {
BatteryStatsImpl.Uid.Proc ps =
bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
prev.info.packageName);
if (ps != null) {
ps.addForegroundTimeLocked(diff);
}
}
}
}
prev.cpuTimeAtResume = 0; // reset it
}
if (mStackSupervisor.mAppVisibilitiesChangedSinceLastPause
|| mService.mStackSupervisor.getStack(PINNED_STACK_ID) != null) {
mService.notifyTaskStackChangedLocked();
mStackSupervisor.mAppVisibilitiesChangedSinceLastPause = false;
}
mStackSupervisor.ensureActivitiesVisibleLocked(resuming, 0, !PRESERVE_WINDOWS);
}
调用了ActivityStackSupervisor
的resumeFocusedStackTopActivityLocked
方法
boolean resumeFocusedStackTopActivityLocked(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
if (targetStack != null && isFocusedStack(targetStack)) {
return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
if (r == null || r.state != RESUMED) {
mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
}
return false;
}
回调了 ActivityStack
的resumeTopActivityUncheckedLocked
方法
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
boolean result = false;
try {
// Protect against recursion.
mStackSupervisor.inResumeTopActivity = true;
if (mService.mLockScreenShown == ActivityManagerService.LOCK_SCREEN_LEAVING) {
mService.mLockScreenShown = ActivityManagerService.LOCK_SCREEN_HIDDEN;
mService.updateSleepIfNeededLocked();
}
result = resumeTopActivityInnerLocked(prev, options);
} finally {
mStackSupervisor.inResumeTopActivity = false;
}
return result;
}
有调用了resumeTopActivityInnerLocked
方法
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
mStackSupervisor.startSpecificActivityLocked(next, true, false);
return true;
}
调用了ActivityStackSupervisor
的startSpecificActivityLocked
方法
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
// Is this activity's application already running?
ProcessRecord app = mService.getProcessRecordLocked(r.processName,
r.info.applicationInfo.uid, true);
r.task.stack.setLaunchTime(r);
if (app != null && app.thread != null) {
try {
if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
|| !"android".equals(r.info.packageName)) {
app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
mService.mProcessStats);
}
realStartActivityLocked(r, app, andResume, checkConfig);
return;
} catch (RemoteException e) {
Slog.w(TAG, "Exception when starting activity "
+ r.intent.getComponent().flattenToShortString(), e);
}
// If a dead object exception was thrown -- fall through to
// restart the application.
}
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);
}
调用了realStartActivityLocked
方法
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
final ActivityStack stack = task.stack;
try {
List<ResultInfo> results = null;
List<ReferrerIntent> newIntents = null;
if (andResume) {
results = r.results;
newIntents = r.newIntents;
}
r.sleeping = false;
r.forceNewConfig = false;
mService.showUnsupportedZoomDialogIfNeededLocked(r);
mService.showAskCompatModeDialogLocked(r);
r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
ProfilerInfo profilerInfo = null;
if (andResume) {
app.hasShownUi = true;
app.pendingUiClean = true;
}
app.forceProcessStateUpTo(mService.mTopProcessState);
app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
new Configuration(task.mOverrideConfig), r.compat, r.launchedFromPackage,
task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);
return true;
}
又是回调了AcitivityThread
的scheduleLaunchActivity
方法。按照前面分析的套路,这里应该又是利用在Handler
发送消息
@Override
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
int procState, Bundle state, PersistableBundle persistentState,
List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
sendMessage(H.LAUNCH_ACTIVITY, r);
}
发送了一个LAUNCH_ACTIVITY
消息
找到处理LAUNCH_ACTIVITY
消息的地方
case LAUNCH_ACTIVITY: {
handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
// If we are getting ready to gc after going to the background, well
// we are back active so skip it.
unscheduleGcIdler();
mSomeActivitiesChanged = true;
if (r.profilerInfo != null) {
mProfiler.setProfiler(r.profilerInfo);
mProfiler.startProfiling();
}
if (localLOGV) Slog.v(
TAG, "Handling launch of " + r);
Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
r.createdConfig = new Configuration(mConfiguration);
reportSizeConfigurations(r);
Bundle oldState = r.state;
handleResumeActivity(r.token, false, r.isForward,
!r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
if (!r.activity.mFinished && r.startsNotResumed) {
performPauseActivityIfNeeded(r, reason);
if (r.isPreHoneycomb()) {
r.state = oldState;
}
}
} else {
// If there was an error, for any reason, tell the activity manager to stop us.
try {
ActivityManagerNative.getDefault()
.finishActivity(r.token, Activity.RESULT_CANCELED, null,
Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
}
调用了performLaunchActivity
方法,这个里面的代码就很明了了。获取Intent
里面的activity
信息,创建一个Activitity
实例出来,如果Application
没有,则创建一个Application
出来。先执行activity
的attach
方法,在设置主题,然后回调onCreate
方法,后又回调onStart
方法。至此我们的activity
就被创建出来了。至于后面的onResume
等等生命周期方法调用方式和这差不多。有兴趣自行分析。
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
// System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
ActivityInfo aInfo = r.activityInfo;
if (r.packageInfo == null) {
r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
Context.CONTEXT_INCLUDE_CODE);
}
ComponentName component = r.intent.getComponent();
if (component == null) {
component = r.intent.resolveActivity(
mInitialApplication.getPackageManager());
r.intent.setComponent(component);
}
if (r.activityInfo.targetActivity != null) {
component = new ComponentName(r.activityInfo.packageName,
r.activityInfo.targetActivity);
}
Activity activity = null;
//通过反射实例Acitivity
try {
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {
if (!mInstrumentation.onException(activity, e)) {
throw new RuntimeException(
"Unable to instantiate activity " + component
+ ": " + e.toString(), e);
}
}
try {
//创建Application
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
if (activity != null) {
Context appContext = createBaseContextForActivity(r, activity);
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Configuration config = new Configuration(mCompatConfiguration);
if (r.overrideConfig != null) {
config.updateFrom(r.overrideConfig);
}
if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
+ r.activityInfo.name + " with config " + config);
Window window = null;
if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
window = r.mPendingRemoveWindow;
r.mPendingRemoveWindow = null;
r.mPendingRemoveWindowManager = null;
}
//执行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);
if (customIntent != null) {
activity.mIntent = customIntent;
}
r.lastNonConfigurationInstances = null;
activity.mStartedActivity = false;
int theme = r.activityInfo.getThemeResource();
if (theme != 0) {
activity.setTheme(theme);
}
activity.mCalled = false;
if (r.isPersistable()) {
//回调OnCreate方法
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
if (!activity.mCalled) {
throw new SuperNotCalledException(
"Activity " + r.intent.getComponent().toShortString() +
" did not call through to super.onCreate()");
}
r.activity = activity;
r.stopped = true;
if (!r.activity.mFinished) {
//回调onStart()方法
activity.performStart();
r.stopped = false;
}
if (!r.activity.mFinished) {
if (r.isPersistable()) {
if (r.state != null || r.persistentState != null) {
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
r.persistentState);
}
} else if (r.state != null) {
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
}
}
if (!r.activity.mFinished) {
activity.mCalled = false;
if (r.isPersistable()) {
mInstrumentation.callActivityOnPostCreate(activity, r.state,
r.persistentState);
} else {
mInstrumentation.callActivityOnPostCreate(activity, r.state);
}
}
}
r.paused = true;
mActivities.put(r.token, r);
}
return activity;
}
Instrumentation
的newActivity
方法
public Activity newActivity(ClassLoader cl, String className,
Intent intent)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
return (Activity)cl.loadClass(className).newInstance();
}
总结:简单说下调用流程,Activity.startActivity()->Instrumentation.execStartActivity()->ActivityManagerService.startActivity调用到系统进程
然后还要回调到app: app.thread.scheduleXXX->ApplicationThread.scheduleXXX->H,利用Handler切换到当前线程
虽然我们只是调用了一句startActivity
方法,但是里面的调用过程去很复杂,涉及到和系统进程通讯。因为activity是四大组件中最复杂的一个,因此如果弄清了activity的调用过程,后面看其他三个组件的调用过程也就不那么费力。
APP和系统双向通讯都是利用Binder
,我们的APP保存了系统服务 的Binder
引用,引用类型是ActivityManagerServer
。但是Binder是单向传输的,所以系统也保留了我们的Binder
引用,应用类型为ActivityThread.ApplicationtThread
.
AcitivityThread.ApplicationtThread
接收到系统的消息利用内部一个H类型变量mH把消息发送给主线程处理