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

int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {

return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,

resultWho, requestCode, startFlags, profilerInfo, bOptions,

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

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

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

img

img

img

img

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

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

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)

最后

总而言之,Android开发行业变化太快,作为技术人员就要保持终生学习的态度,让学习力成为核心竞争力,所谓“活到老学到老”只有不断的学习,不断的提升自己,才能跟紧行业的步伐,才能不被时代所淘汰。

在这里我分享一份自己收录整理上述技术体系图相关的几十套腾讯、头条、阿里、美团等公司20年的面试题,把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节,由于篇幅有限,这里以图片的形式给大家展示一部分。

还有高级架构技术进阶脑图、Android开发面试专题资料,高级进阶架构资料 帮助大家学习提升进阶,也节省大家在网上搜索资料的时间来学习,也可以分享给身边好友一起学习。

《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!

OYMVjN3-1713264863969)]

[外链图片转存中…(img-eodhJcrW-1713264863970)]

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

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

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)

最后

总而言之,Android开发行业变化太快,作为技术人员就要保持终生学习的态度,让学习力成为核心竞争力,所谓“活到老学到老”只有不断的学习,不断的提升自己,才能跟紧行业的步伐,才能不被时代所淘汰。

在这里我分享一份自己收录整理上述技术体系图相关的几十套腾讯、头条、阿里、美团等公司20年的面试题,把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节,由于篇幅有限,这里以图片的形式给大家展示一部分。

[外链图片转存中…(img-SP1oHM62-1713264863971)]

[外链图片转存中…(img-BYpkqm7o-1713264863972)]

[外链图片转存中…(img-sBzacZsT-1713264863973)]

还有高级架构技术进阶脑图、Android开发面试专题资料,高级进阶架构资料 帮助大家学习提升进阶,也节省大家在网上搜索资料的时间来学习,也可以分享给身边好友一起学习。

《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值