[java] view plain copy
-
/*package*/ static void checkStartActivityResult(int res, Object intent) {
-
if (res >= ActivityManager.START_SUCCESS) {
-
return;
-
}
-
switch (res) {
-
case ActivityManager.START_INTENT_NOT_RESOLVED:
-
case ActivityManager.START_CLASS_NOT_FOUND:
-
if (intent instanceof Intent && ((Intent)intent).getComponent() != null)
-
throw new ActivityNotFoundException(
-
"Unable to find explicit activity class "
-
+ ((Intent)intent).getComponent().toShortString()
-
+ “; have you declared this activity in your AndroidManifest.xml?”);
-
throw new ActivityNotFoundException(
-
"No Activity found to handle " + intent);
-
case ActivityManager.START_PERMISSION_DENIED:
-
throw new SecurityException("Not allowed to start activity "
-
+ intent);
-
case ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT:
-
throw new AndroidRuntimeException(
-
“FORWARD_RESULT_FLAG used while also requesting a result”);
-
case ActivityManager.START_NOT_ACTIVITY:
-
throw new IllegalArgumentException(
-
“PendingIntent is not an activity”);
-
default:
-
throw new AndroidRuntimeException("Unknown error code "
-
+ res + " when starting " + intent);
-
}
-
}
接下来我们要去看看IApplicationThread,因为核心功能由其内部的scheduleLaunchActivity方法来完成,由于IApplicationThread是个接口,所以,我们需要找到它的实现类,我已经帮大家找到了,它就是ActivityThread中的内部类ApplicationThread,看下它的继承关系:
private class ApplicationThread extends ApplicationThreadNative;
public abstract class ApplicationThreadNative extends Binder implements IApplicationThread;
可以发现,ApplicationThread还是间接实现了IApplicationThread接口,先看下这个类的结构
看完ApplicationThread的大致结构,我们应该能够猜测到,Activity的生命周期中的resume、newIntent、pause、stop等事件都是由它触发的,事实上,的确是这样的。这里,我们为了说明问题,仅仅看scheduleLaunchActivity方法
code:ApplicationThread#scheduleLaunchActivity
[java] view plain copy
-
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
-
ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
-
int procState, Bundle state, List pendingResults,
-
List pendingNewIntents, boolean notResumed, boolean isForward,
-
String profileName, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
-
updateProcessState(procState, false);
-
ActivityClientRecord r = new ActivityClientRecord();
-
r.token = token;
-
r.ident = ident;
-
r.intent = intent;
-
r.activityInfo = info;
-
r.compatInfo = compatInfo;
-
r.state = state;
-
r.pendingResults = pendingResults;
-
r.pendingIntents = pendingNewIntents;
-
r.startsNotResumed = notResumed;
-
r.isForward = isForward;
-
r.profileFile = profileName;
-
r.profileFd = profileFd;
-
r.autoStopProfiler = autoStopProfiler;
-
updatePendingConfiguration(curConfig);
-
queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
-
}
说明:上述代码很好理解,构造一个activity记录,然后发送一个消息,所以,我们要看看Handler是如何处理这个消息的,现在转到这个Handler,它有个很短的名字叫做H
code:ActivityThread#H
[java] view plain copy
-
//这个类太长,我只帖出了我们用到的部分
-
private class H extends Handler {
-
public void handleMessage(Message msg) {
-
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
-
switch (msg.what) {
-
//这里处理LAUNCH_ACTIVITY消息类型
-
case LAUNCH_ACTIVITY: {
-
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, “activityStart”);
-
ActivityClientRecord r = (ActivityClientRecord)msg.obj;
-
r.packageInfo = getPackageInfoNoCheck(
-
r.activityInfo.applicationInfo, r.compatInfo);
-
//这里处理startActivity消息
-
handleLaunchActivity(r, null);
-
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
-
} break;
-
case RELAUNCH_ACTIVITY: {
-
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, “activityRestart”);
-
ActivityClientRecord r = (ActivityClientRecord)msg.obj;
-
handleRelaunchActivity®;
-
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
-
} break;
-
case PAUSE_ACTIVITY:
-
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, “activityPause”);
-
handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
-
maybeSnapshot();
-
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
-
break;
-
…
-
}
-
}
说明:看来还要看handleLaunchActivity
code:ActivityThread#handleLaunchActivity
[java] view plain copy
-
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
-
// If we are getting ready to gc after going to the background, well
-
// we are back active so skip it.
-
unscheduleGcIdler();
-
if (r.profileFd != null) {
-
mProfiler.setProfiler(r.profileFile, r.profileFd);
-
mProfiler.startProfiling();
-
mProfiler.autoStopProfiler = r.autoStopProfiler;
-
}
-
// Make sure we are running with the most recent config.
-
handleConfigurationChanged(null, null);
-
if (localLOGV) Slog.v(
-
TAG, "Handling launch of " + r);
-
//终于到底了,大家都有点不耐烦了吧,从方法名可以看出,
-
//performLaunchActivity真正完成了activity的调起,
-
//同时activity会被实例化,并且onCreate会被调用
-
Activity a = performLaunchActivity(r, customIntent);
-
if (a != null) {
-
r.createdConfig = new Configuration(mConfiguration);
-
Bundle oldState = r.state;
-
//看到没,目标activity的onResume会被调用
-
handleResumeActivity(r.token, false, r.isForward,
-
!r.activity.mFinished && !r.startsNotResumed);
-
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.
-
try {
-
r.activity.mCalled = false;
-
//同时,由于新activity被调起了,原activity的onPause会被调用
-
mInstrumentation.callActivityOnPause(r.activity);
-
// 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;
-
}
-
if (!r.activity.mCalled) {
-
throw new SuperNotCalledException(
-
"Activity " + r.intent.getComponent().toShortString() +
-
" 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 "
-
+ r.intent.getComponent().toShortString()
-
+ ": " + e.toString(), e);
-
}
-
}
-
r.paused = true;
-
}
-
} 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);
-
} catch (RemoteException ex) {
-
// Ignore
-
}
-
}
-
}
说明:关于原activity和新activity之间的状态同步,如果大家感兴趣可以自己研究下,因为逻辑太复杂,我没法把所有问题都说清楚,否则就太深入细节而淹没了整体逻辑,研究源码要的就是清楚整体逻辑。下面看最后一个方法,这个方法是activity的启动过程的真正实现。
code:ActivityThread#performLaunchActivity
[java] view plain copy
-
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);
-
}
-
//首先从intent中解析出目标activity的启动参数
-
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;
-
try {
-
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
-
//用ClassLoader(类加载器)将目标activity的类通过类名加载进来并调用newInstance来实例化一个对象
-
//其实就是通过Activity的无参构造方法来new一个对象,对象就是在这里new出来的。
-
activity = mInstrumentation.newActivity(
-
cl, component.getClassName(), r.intent);
-
StrictMode.incrementExpectedActivityCount(activity.getClass());
-
r.intent.setExtrasClassLoader(cl);
-
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 app = r.packageInfo.makeApplication(false, mInstrumentation);
-
if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
-
if (localLOGV) Slog.v(
-
TAG, r + “: app=” + app
-
+ “, appName=” + app.getPackageName()
-
+ “, pkg=” + r.packageInfo.getPackageName()
-
+ “, comp=” + r.intent.getComponent().toShortString()
-
+ “, dir=” + r.packageInfo.getAppDir());
-
if (activity != null) {
-
Context appContext = createBaseContextForActivity(r, activity);
-
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
-
Configuration config = new Configuration(mCompatConfiguration);
-
if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
-
+ r.activityInfo.name + " with config " + config);
-
activity.attach(appContext, this, getInstrumentation(), r.token,
-
r.ident, app, r.intent, r.activityInfo, title, r.parent,
-
r.embeddedID, r.lastNonConfigurationInstances, config);
-
if (customIntent != null) {
-
activity.mIntent = customIntent;
-
}
-
r.lastNonConfigurationInstances = null;
-
activity.mStartedActivity = false;
-
int theme = r.activityInfo.getThemeResource()
-
if (theme != 0) {
尾声
面试成功其实都是必然发生的事情,因为在此之前我做足了充分的准备工作,不单单是纯粹的刷题,更多的还会去刷一些Android核心架构进阶知识点,比如:JVM、高并发、多线程、缓存、热修复设计、插件化框架解读、组件化框架设计、图片加载框架、网络、设计模式、设计思想与代码质量优化、程序性能优化、开发效率优化、设计模式、负载均衡、算法、数据结构、高级UI晋升、Framework内核解析、Android组件内核等。
不仅有学习文档,视频+笔记提高学习效率,还能稳固你的知识,形成良好的系统的知识体系。这里,笔者分享一份从架构哲学的层面来剖析的视频及资料分享给大家梳理了多年的架构经验,筹备近6个月最新录制的,相信这份视频能给你带来不一样的启发、收获。
Android进阶学习资料库
一共十个专题,包括了Android进阶所有学习资料,Android进阶视频,Flutter,java基础,kotlin,NDK模块,计算机网络,数据结构与算法,微信小程序,面试题解析,framework源码!
大厂面试真题
PS:之前因为秋招收集的二十套一二线互联网公司Android面试真题 (含BAT、小米、华为、美团、滴滴)和我自己整理Android复习笔记(包含Android基础知识点、Android扩展知识点、Android源码解析、设计模式汇总、Gradle知识点、常见算法题汇总。)
《2017-2021字节跳动Android面试历年真题解析》
好的系统的知识体系。这里,笔者分享一份从架构哲学的层面来剖析的视频及资料分享给大家梳理了多年的架构经验,筹备近6个月最新录制的,相信这份视频能给你带来不一样的启发、收获。
[外链图片转存中…(img-dcYiNXzr-1726046011798)]
Android进阶学习资料库
一共十个专题,包括了Android进阶所有学习资料,Android进阶视频,Flutter,java基础,kotlin,NDK模块,计算机网络,数据结构与算法,微信小程序,面试题解析,framework源码!
[外链图片转存中…(img-Y6VR4VKW-1726046011799)]
大厂面试真题
PS:之前因为秋招收集的二十套一二线互联网公司Android面试真题 (含BAT、小米、华为、美团、滴滴)和我自己整理Android复习笔记(包含Android基础知识点、Android扩展知识点、Android源码解析、设计模式汇总、Gradle知识点、常见算法题汇总。)
[外链图片转存中…(img-TIxvrfLH-1726046011799)]
《2017-2021字节跳动Android面试历年真题解析》
[外链图片转存中…(img-Jh26HkJm-1726046011799)]