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

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,

!r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);

if (!r.activity.mFinished && r.startsNotResumed) {

// The activity manager actually wants this one to start out paused, because it

// needs to be visible but isn’t in the foreground. We accomplish this by going

// through the normal startup (because activities expect to go through onResume()

// the first time they run, before their window is displayed), and then pausing it.

// However, in this case we do -not- need to do the full pause cycle (of freezing

// and such) because the activity manager assumes it can just retain the current

// state it has.

performPauseActivityIfNeeded(r, reason);

// We need to keep around the original state, in case we need to be created again.

// But we only do this for pre-Honeycomb apps, which always save their state when

// pausing, so we can not have them save their state when restarting from a paused

// state. For HC and later, we want to (and can) let the state be saved as the

// normal part of stopping the activity.

if (r.isPreHoneycomb()) {

r.state = oldState;

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
img
img
img
img
img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以添加V获取:vip204888 (备注Android)
img

推荐学习资料

  • Android进阶学习全套手册

  • Android对标阿里P7学习视频

  • BAT TMD大厂Android高频面试题

一个人可以走的很快,但一群人才能走的更远。不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎扫码加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
img
y4paU-1712777547046)]
[外链图片转存中…(img-oYtSCMvB-1712777547046)]
[外链图片转存中…(img-CEoiUhCa-1712777547047)]
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以添加V获取:vip204888 (备注Android)
[外链图片转存中…(img-HVWOAVmU-1712777547047)]

推荐学习资料

  • Android进阶学习全套手册

    [外链图片转存中…(img-ty0QU7Sz-1712777547047)]

  • Android对标阿里P7学习视频

    [外链图片转存中…(img-FIeWlcEG-1712777547047)]

  • BAT TMD大厂Android高频面试题

[外链图片转存中…(img-gUxe6Ib0-1712777547048)]

一个人可以走的很快,但一群人才能走的更远。不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎扫码加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
[外链图片转存中…(img-4eLSV3av-1712777547048)]

  • 8
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值