Android插件化架构 - Activity的启动流程分析

UserHandle.getCallingUserId());

}

@Override

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) {

enforceNotIsolatedCaller(“startActivity”);

userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),

userId, false, ALLOW_FULL_ONLY, “startActivity”, null);

// TODO: Switch to user app stacks here.

return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,

resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,

profilerInfo, null, null, bOptions, false, userId, null, null);

}

final 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, IActivityManager.WaitResult outResult, Configuration config,

Bundle bOptions, boolean ignoreTargetSecurity, int userId,

IActivityContainer iContainer, TaskRecord inTask) {

// PackageManagerService-----> 扫描app,注册组件

ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId);

// Collect information about the target of the Intent.

ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);

rInfo = mSupervisor.resolveIntent(intent, null /resolvedType/, userId);

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);

}

final int startActivityLocked(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,

ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,

ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,

TaskRecord inTask) {

// 验证intent、Class、Permission等

// 保存将要启动的Activity的Record

err = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor, startFlags,

true, options, inTask);

return err;

}

private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,

IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,

int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask) {

// 检查将要启动的Activity的launchMode和启动Flag

// 根据launcheMode和Flag配置task

final boolean dontStart = top != null && mStartActivity.resultTo == null

&& top.realActivity.equals(mStartActivity.realActivity)

&& top.userId == mStartActivity.userId

&& top.app != null && top.app.thread != null

&& ((mLaunchFlags & FLAG_ACTIVITY_SINGLE_TOP) != 0

|| mLaunchSingleTop || mLaunchSingleTask);

// 举一个例子 SingleTop

if (dontStart) {

top.deliverNewIntentLocked(

mCallingUid, mStartActivity.intent, mStartActivity.launchedFromPackage);

// Don’t use mStartActivity.task to show the toast. We’re not starting a new activity

// but reusing ‘top’. Fields in mStartActivity may not be fully initialized.

mSupervisor.handleNonResizableTaskIfNeeded(

top.task, preferredLaunchStackId, topStack.mStackId);

return START_DELIVERED_TO_TOP;

}

mTargetStack.startActivityLocked(mStartActivity, newTask, mKeepCurTransition, mOptions);

if (mDoResume) {

mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,

mOptions);

}

}

进入ActvityStack中的startActivityLocked()方法

// 任务栈历史栈配置

final void startActivityLocked(ActivityRecord r, boolean newTask, boolean keepCurTransition,

ActivityOptions options) {

if (!r.mLaunchTaskBehind && (taskForIdLocked(taskId) == null || newTask)) {

// 加入栈顶 管理栈

insertTaskAtTop(rTask, r);

// 管显示

mWindowManager.moveTaskToTop(taskId);

}

if (!newTask) {

// 不是一个新的Task

task.addActivityToTop®;

r.putInHistory();

addConfigOverride(r, task);

}

}

进入ActivityStack的resumeTopActivityInnerLocked()方法

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {

// Find the first activity that is not finishing.

final ActivityRecord next = topRunningActivityLocked();

// The activity may be waiting for stop, but that is no longer

// appropriate for it.

mStackSupervisor.mStoppingActivities.remove(next);

mStackSupervisor.mGoingToSleepActivities.remove(next);

next.sleeping = false;

mStackSupervisor.mWaitingVisibleActivities.remove(next);

if (mResumedActivity != null) {

if (DEBUG_STATES) Slog.d(TAG_STATES,

"resumeTopActivityLocked: Pausing " + mResumedActivity);

pausing |= startPausingLocked(userLeaving, false, next, dontWaitForPause);

}

}

final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,

ActivityRecord resuming, boolean dontWait) {

if (prev.app != null && prev.app.thread != null) {

if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Enqueueing pending pause: " + prev);

try {

EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,

prev.userId, System.identityHashCode(prev),

prev.shortComponentName);

mService.updateUsageStats(prev, false);

// 暂停Activity

prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,

userLeaving, prev.configChangeFlags, dontWait);

}

completePauseLocked(false, resuming);

}

进入ApplicationThread的schedulePauseActivity()方法

public final void schedulePauseActivity(IBinder token, boolean finished,

boolean userLeaving, int configChanges, boolean dontReport) {

sendMessage(

finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,

token,

(userLeaving ? USER_LEAVING : 0) | (dontReport ? DONT_REPORT : 0),

configChanges,

seq);

}

public void handleMessage(Message msg) {

switch (msg.what) {

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;

}

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 {

ActivityManagerNative.getDefault().activityPaused(token);

} catch (RemoteException ex) {

throw ex.rethrowFromSystemServer();

}

}

}

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;

}

final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,

boolean saveState, String reason) {

// …

performPauseActivityIfNeeded(r, reason);

}

private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {

// …

mInstrumentation.callActivityOnPause(r.activity);

}

进入Instrumentation的callActivityOnPause()方法

public void callActivityOnPause(Activity activity) {

activity.performPause();

}

进入Activity的performPause()方法

final void performPause() {

mDoReportFullyDrawn = false;

mFragments.dispatchPause();

mCalled = false;

// 调用onPause()暂停方法

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;

}

总算是回调到了Activity的onPause方法,哈哈还是挺简单的,Activity生命周期中的onPause方法终于被我们找到了。也就是说我们在启动一个Activity的时候最先被执行的是栈顶的Activity的onPause方法。我们对Activity这些生命周期早已背得滚瓜烂熟。接着往下看然后回到我们ApplicationThread的handlePauseActivity()方法中的ActivityManagerNative.getDefault().activityPaused(token);进入ActivityManagerService中的activityPaused()方法

@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){

completePauseLocked(true, null);

}

private void completePauseLocked(boolean resumeNext, ActivityRecord resuming) {

ActivityRecord prev = mPausingActivity;

if (resumeNext) {

final ActivityStack topStack = mStackSupervisor.getFocusedStack();

mStackSupervisor.resumeFocusedStackTopActivityLocked(topStack, prev, null);

}

}

进入ActivityStackSupervisor中的resumeFocusedStackTopActivityLocked()方法

boolean resumeFocusedStackTopActivityLocked(

ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {

targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);

}

进入ActivityStack中的resumeTopActivityUncheckedLocked()方法

boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {

result = resumeTopActivityInnerLocked(prev, options);

}

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {

// 这个方法我们已经很熟悉了

mStackSupervisor.startSpecificActivityLocked(next, true, 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®;

if (app != null && app.thread != null) {

try {

if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0

|| !“android”.equals(r.info.packageName)) {

// Don’t add this if it is a platform component that is marked

// to run in multiple processes, because this is actually

// part of the framework so doesn’t make sense to track as a

// separate apk in the process.

app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,

mService.mProcessStats);

}

// 真的要启动Activity了

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);

}

final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,

boolean andResume, boolean checkConfig) throws RemoteException {

// scheduleLaunchActivity 启动

app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,

System.identityHashCode®, 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);

}

进入ApplicationThread中的scheduleLaunchActivity()方法

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 pendingResults, List pendingNewIntents,

boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {

updateProcessState(procState, false);

ActivityClientRecord r = new ActivityClientRecord();

r.token = token;

r.ident = ident;

r.intent = intent;

r.referrer = referrer;

r.voiceInteractor = voiceInteractor;

r.activityInfo = info;

r.compatInfo = compatInfo;

r.state = state;

r.persistentState = persistentState;

r.pendingResults = pendingResults;

r.pendingIntents = pendingNewIntents;

r.startsNotResumed = notResumed;

r.isForward = isForward;

r.profilerInfo = profilerInfo;

r.overrideConfig = overrideConfig;

updatePendingConfiguration(curConfig);

sendMessage(H.LAUNCH_ACTIVITY, r);

}

public void handleMessage(Message msg) {

if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));

switch (msg.what) {

case LAUNCH_ACTIVITY: {

Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, “activityStart”);

final ActivityClientRecord r = (ActivityClientRecord) msg.obj;

r.packageInfo = getPackageInfoNoCheck(

r.activityInfo.applicationInfo, r.compatInfo);

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();

}

// Make sure we are running with the most recent config.

handleConfigurationChanged(null, null);

if (localLOGV) Slog.v(

TAG, "Handling launch of " + r);

// Initialize before creating the activity

WindowManagerGlobal.initialize();

Activity a = performLaunchActivity(r, customIntent);

if (a != null) {

r.createdConfig = new Configuration(mConfiguration);

reportSizeConfigurations®;

Bundle oldState = r.state;

handleResumeActivity(r.token, false, r.isForward,

最后

我这里整理了一份完整的学习思维以及Android开发知识大全PDF。

当然实践出真知,即使有了学习线路也要注重实践,学习过的内容只有结合实操才算是真正的掌握。
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!
;

if (r.profilerInfo != null) {

mProfiler.setProfiler(r.profilerInfo);

mProfiler.startProfiling();

}

// Make sure we are running with the most recent config.

handleConfigurationChanged(null, null);

if (localLOGV) Slog.v(

TAG, "Handling launch of " + r);

// Initialize before creating the activity

WindowManagerGlobal.initialize();

Activity a = performLaunchActivity(r, customIntent);

if (a != null) {

r.createdConfig = new Configuration(mConfiguration);

reportSizeConfigurations®;

Bundle oldState = r.state;

handleResumeActivity(r.token, false, r.isForward,

最后

我这里整理了一份完整的学习思维以及Android开发知识大全PDF。

[外链图片转存中…(img-SwmZHm4D-1714552276406)]

当然实践出真知,即使有了学习线路也要注重实践,学习过的内容只有结合实操才算是真正的掌握。
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!

  • 18
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值