App starts
- 1. App startup flow chart
- 2. Detailed interpretation of the flow chart
-
- 2.1. System operation
- 2.2. Process starts
-
- Step 3. ActivityThread is loaded into memory
- Step 3.2, ActivityThread.main()
- Step 4. ActivityManagerService.attachApplication()
- Step 5.1
- Step 6.1, ApplicationThread.bindApplication()
- Step 7.1, ActivityThread.H receives
- Step 5.2,
- Step 6.2, ApplicationThread.scheduleLaunchActivity()
- Step 7.2, ActivityThread.H receives
- Step 8.2, handleLaunchActivity
- 3. API
- Reference address
1. App startup flow chart
The method is slightly different after Android update. The following is the source code of around 8.
https://www.jianshu.com/p/538dcfac774d
Brief description:
-
When the desktop application icon is clicked, the Launcher's
startActivity()
method calls thestartActivity
method of the ActivityManagerService (AMS) in the system process through Binder communication to start the application. program. -
After receiving the request, the system process (system_server) sends a request to create an application process to the Zygote process.
-
The Zygote process forks out of the application process according to the request and executes the application's
ActivityThread.main()
method. During this process, the main thread of the application initializes the MainLooper and the main thread Handler, and createsApplicationThread
for communication and collaboration with AMS. -
The application process sends a request to the system_server process
attachApplication
through Binder. This is actually the application process calling the AMS method in the system_server process through Binder, which is used to bind the object to AMS.attachApplication
ApplicationThread
-
attachApplication
After receiving the request, the request (used to create a startup Activity). method) andhandleBindApplication
request to the application process through Binder IPC (for initialization Application and calls the system_server process performs some preparation work, and then sends theonCreate
scheduleLaunchActivity
-
After receiving the request, the Binder thread (
ApplicationThread
) of the application process sendsBIND_APPLICATION
and , and then interact through Handler messages.LAUNCH_ACTIVITY
ApplicationThread
-
After receiving the message, the main thread creates
Application
and calls theonCreate
method, then creates the target Activity through the reflection mechanism and calls back the Activity's methods in sequence to complete UI rendering and Displays the main interface of the application. , ,onCreate
and other methods. At this point, the application is officially started and enters the Activity life cycle, executing theonCreate
onStart
onResume
2. Detailed interpretation of the flow chart
2.1. System operation
Incubation of Zygote processes
- Before the application starts, the system usually starts the Zygote process. The Zygote process will preload some system libraries and resources in the background to speed up the creation of the process.
- The Zygote process internally executes the
main()
method, creates an Android Runtime environment, and waits for requests from new application processes.
Application resources and class loading
- When the user starts the application or triggers other application components, the Zygote process loads the application's resources (such as layout files, string resources, etc.) and classes according to the application's package name.
- The Zygote process will act as a template for the application process, loading the application's code and resources based on the application's package name and required resources.
App shows blank launch window of app immediately after launch
Who created the blank window? ?
During the startup process of an Android application, this short-lived background is usually automatically created and managed by the system without direct intervention by the developer. Specifically, the creation and display of this background is handled by the Android system's window management service and system framework.
The Android system displays this background when the app starts to provide user feedback and initialize the app in the background. This background is displayed before the application's main activity is ready and starts displaying the user interface.
Developers can customize this ephemeral background by setting the app's theme and splash screen. Themes and splash screens are part of the app's appearance and launch process, allowing developers to specify the app's logo, colors, background, and more. Your app's theme and splash screen settings can be defined in the AndroidManifest.xml file.
In summary, this ephemeral background is automatically created and managed by the Android system to provide user feedback and smooth app launch transitions. It does not require developers to create or operate directly.
Create application process
Application Process:
The application process is an independent execution unit that runs applications in the Android operating system.
Each application runs in its own application process, which means that each application has an independent memory space, an independent virtual machine (Dalvik or ART), and an independent running environment. .
The application process is responsible for executing various components of the application, such as Activity, Service, Broadcast Receiver, etc. Each component runs within the application process.
The life cycle of the application process is managed by the Android system, and the system can create, destroy or restart the application process when needed.
2.2. Process starts
Step 3. ActivityThread is loaded into memory
ActivityThread.main() is called after the process is created, but it does not start the Activity immediately after the main thread is created, but continues to communicate with AMS.
https://www.cnblogs.com/mingfeng002/p/10323668.html
In addition, ActivityThread represents the main thread of Android in Android, but it is not a Thread class.
Strictly speaking, the UI main thread is not ActivityThread.
The ActivityThread class is the initial class of the Android APP process, and its main function is the entrance to the APP process.
The execution code segments of UI events in the APP process are provided by ActivityThread.
In other words, the Main Thread instance exists, but the code that creates it is not visible to us. The main function of ActivityThread is executed in this Main Thread.
Step 3.2, ActivityThread.main()
public static void main(String[] args) {
//各种初始化操作,省略
//初始化主线程的Looper,一个线程只能有一个Looper
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
//在attach方法中会完成Application对象的初始化,然后调用Application的onCreate()方法
thread.attach(false, startSeq);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
//在主线程开启循环读取消息队列中的消息
Looper.loop();
}
private void attach(boolean system, long startSeq) {
sCurrentActivityThread = this;
mSystemThread = system;
if (!system) {
//如果应用进程
android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
UserHandle.myUserId());
//将mAppThread放到RuntimeInit类中的静态变量,也就是ApplicationThreadNative中的 this
RuntimeInit.setApplicationObject(mAppThread.asBinder());
//跨进程通讯,获取AMS在APP进程的代理
final IActivityManager mgr = ActivityManager.getService();
try {
//将mAppThread传入ActivityManagerService中
mgr.attachApplication(mAppThread, startSeq);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
// 监听内存限制
BinderInternal.addGcWatcher(new Runnable() {
@Override public void run() {
if (!mSomeActivitiesChanged) {
return;
}
Runtime runtime = Runtime.getRuntime();
long dalvikMax = runtime.maxMemory();
long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
//当虚拟机已使用内存超过最大内存的四分之三时,ActivityTaskManager释放一些Activity
if (dalvikUsed > ((3*dalvikMax)/4)) {
mSomeActivitiesChanged = false;
try {
ActivityTaskManager.getService().releaseSomeActivities(mAppThread);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
}
});
} else {
//通过system_server启动ActivityThread对象
...
}
// 为 ViewRootImpl 设置配置更新回调,
ViewRootImpl.ConfigChangedCallback configChangedCallback
= (Configuration globalConfig) -> {
synchronized (mResourcesManager) {
....
}
};
//添加配置回调
ViewRootImpl.addConfigCallback(configChangedCallback);
}
Step 4. ActivityManagerService.attachApplication()
7020 @Override
7021 public final void attachApplication(IApplicationThread thread) {
7022 synchronized (this) {
7023 int callingPid = Binder.getCallingPid();
7024 final long origId = Binder.clearCallingIdentity();
7025 attachApplicationLocked(thread, callingPid);
7026 Binder.restoreCallingIdentity(origId);
7027 }
7028 }
private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
int pid, int callingUid, long startSeq) {
....
//ApplicationThread调用bindApplication,ApplicationThread是ActivityThread的内部类
thread.bindApplication(processName, appInfo, providerList,···);
....
//查看这个进程中是否有顶部可见的activity正在等待运行…(10以后的版本,之前跟这基本一致)
6955 // See if the top visible activity is waiting to run in this process...
6956 if (normalMode) {
6957 try {
6958 if (mStackSupervisor.attachApplicationLocked(app)) {
6959 didSomething = true;
6960 }
6961 } catch (Exception e) {
6962 Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
6963 badApp = true;
6964 }
6965 }
6967 // Find any services that should be running in this process...
6968 if (!badApp) {
6969 try {
6970 didSomething |= mServices.attachApplicationLocked(app, processName);
6971 checkTime(startTime, "attachApplicationLocked: after mServices.attachApplicationLocked");
6972 } catch (Exception e) {
6973 Slog.wtf(TAG, "Exception thrown starting services in " + app, e);
6974 badApp = true;
6975 }
6976 }
....
}
Step 5.1
As above
thread.bindApplication(processName, appInfo, providerList,···);
The thread in the method is IApplicationThread, which is the agent of ApplicationThread in AMS.
Step 6.1, ApplicationThread.bindApplication()
Send bindApplication message to ActivityThread's Handler
public final void bindApplication(String processName, ...
ContentCaptureOptions contentCaptureOptions, long[] disabledCompatChanges) {
if (services != null) {
ServiceManager.initServiceCache(services);
}
setCoreSettings(coreSettings);
AppBindData data = new AppBindData();
data.processName = processName;
....
sendMessage(H.BIND_APPLICATION, data);
}
Step 7.1, ActivityThread.H receives
BIND_APPLICATION
Handler receives the message and processes BindApplication
1658 case BIND_APPLICATION:
1659 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
1660 AppBindData data = (AppBindData)msg.obj;
1661 handleBindApplication(data);
1662 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1663 break;
Various initializations, creating application instances and calling application's onCreate
private void handleBindApplication(AppBindData data) {
//在运行时将当前执行线程注册为敏感线程
VMRuntime.registerSensitiveThread();
...
//标记进程起始时间
Process.setStartTimes(SystemClock.elapsedRealtime(), SystemClock.uptimeMillis());
...
//设置进程名字
Process.setArgV0(data.processName);
//设置一个标记位,androidQ及以上版本一些不明确数组相关的类会抛出数组越界异常
//例如[SparseArray的keyAt和setValueAt在Q之前的版本不会抛出异常](/https://blog.csdn.net/wzz18749670290/article/details/109352466)
UtilConfig.setThrowExceptionForUpperArrayOutOfBounds(
data.appInfo.targetSdkVersion >= Build.VERSION_CODES.Q);
//androidP之前用BitmapFactory解码Bitmap,会放大density。android P及以后,用ImageDecoder解码Bitmap,会跳过upscale节约内存
ImageDecoder.sApiLevel = data.appInfo.targetSdkVersion;
//重置系统时区
TimeZone.setDefault(null);
//断点调试相关
if (data.debugMode != ApplicationThreadConstants.DEBUG_OFF) {
// XXX should have option to change the port.
...
}
...
//渲染调试相关
boolean isAppDebuggable = (data.appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
HardwareRenderer.setDebuggingEnabled(isAppDebuggable || Build.IS_DEBUGGABLE);
HardwareRenderer.setPackageName(data.appInfo.packageName);
//初始化HTTP代理
final IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
if (b != null) {
final IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
try {
Proxy.setHttpProxySystemProperty(service.getProxyForNetwork(null));
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
//创建Instrumentation并初始化
// Continue loading instrumentation.
if (ii != null) {
ApplicationInfo instrApp;
try {
instrApp = getPackageManager().getApplicationInfo(ii.packageName, 0,
UserHandle.myUserId());
} catch (RemoteException e) {
instrApp = null;
}
if (instrApp == null) {
instrApp = new ApplicationInfo();
}
ii.copyTo(instrApp);
instrApp.initForUser(UserHandle.myUserId());
final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
appContext.getClassLoader(), false, true, false);
final ContextImpl instrContext = ContextImpl.createAppContext(this, pi,
appContext.getOpPackageName());
try {
//通过ClassLoader创建Instrumentation
final ClassLoader cl = instrContext.getClassLoader();
mInstrumentation = (Instrumentation)
cl.loadClass(data.instrumentationName.getClassName()).newInstance();
} catch (Exception e) {
...
}
//初始化Instrumentation
final ComponentName component = new ComponentName(ii.packageName, ii.name);
mInstrumentation.init(this, instrContext, appContext, component,
data.instrumentationWatcher, data.instrumentationUiAutomationConnection);
} else {
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
}
...
Application app;
try {
//创建application,这里面会调用application的attachBaseContext,这里的info对应的class是LoadedApk.java,最终也是通过classLoader创建Application
app = data.info.makeApplication(data.restrictedBackupMode, null);
...
if (!data.restrictedBackupMode) {
if (!ArrayUtils.isEmpty(data.providers)) {
//这里调用installProvider()->AppComponentFactory.instantiateProvider->
//localProvider.attachInfo()->ContentProvider.onCreate();
//看到这里就明白了为什么LeakCanary2.0不需要在Application中手动初始化
installContentProviders(app, data.providers);
}
}
//调用application的onCreate
mInstrumentation.callApplicationOnCreate(app);
}
//预加载字体资源
FontsContract.setApplicationContextForResources(appContext);
...
}
Before mInstrumentation.newApplication, the App's Context was created, and the specific implementation class is ContextImpl
Then the Context is passed in when creating the App, that is, the App holds the Context
After creating the App, ContextImpl calls setOuterContext(app), so that the Context holds a reference to the App. This is why we can context.getApplicationContext()
LoadedApk.makeApplication()
http://androidxref.com/6.0.0_r1/xref/frameworks/base/core/java/android/app/LoadedApk.java
554 public Application makeApplication(boolean forceDefaultAppClass,
555 Instrumentation instrumentation) {
556 if (mApplication != null) {
557 return mApplication;
558 }
559
560 Application app = null;
561
562 String appClass = mApplicationInfo.className;
563 if (forceDefaultAppClass || (appClass == null)) {
564 appClass = "android.app.Application";
565 }
566
567 try {
568 java.lang.ClassLoader cl = getClassLoader();
569 if (!mPackageName.equals("android")) {
570 initializeJavaContextClassLoader();
571 }
572 ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
573 app = mActivityThread.mInstrumentation.newApplication(
574 cl, appClass, appContext);
575 appContext.setOuterContext(app);
576 } catch (Exception e) {
577 if (!mActivityThread.mInstrumentation.onException(app, e)) {
578 throw new RuntimeException(
579 "Unable to instantiate application " + appClass
580 + ": " + e.toString(), e);
581 }
582 }
583 mActivityThread.mAllApplications.add(app);
584 mApplication = app;
585
586 if (instrumentation != null) {
587 try {
588 instrumentation.callApplicationOnCreate(app);
589 } catch (Exception e) {
590 if (!instrumentation.onException(app, e)) {
591 throw new RuntimeException(
592 "Unable to create application " + app.getClass().getName()
593 + ": " + e.toString(), e);
594 }
595 }
596 }
597
598 // Rewrite the R 'constants' for all library apks.
599 SparseArray<String> packageIdentifiers = getAssets(mActivityThread)
600 .getAssignedPackageIdentifiers();
601 final int N = packageIdentifiers.size();
602 for (int i = 0; i < N; i++) {
603 final int id = packageIdentifiers.keyAt(i);
604 if (id == 0x01 || id == 0x7f) {
605 continue;
606 }
607
608 rewriteRValues(getClassLoader(), packageIdentifiers.valueAt(i), id);
609 }
610
611 return app;
612 }
Instrumentation.newApplication()
http://androidxref.com/6.0.0_r1/xref/frameworks/base/core/java/android/app/Instrumentation.java
public Application newApplication(ClassLoader cl, String className, Context context)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
Application app = getFactory(context.getPackageName())
.instantiateApplication(cl, className);
//调用Application的attach
app.attach(context);
return app;
}
public void callApplicationOnCreate(Application app) {
//调用Application的onCreate
app.onCreate();
}
Step 5.2,
(mStackSupervisor.attachApplicationLocked(app))
MeetingActivityStackSupervisor
Meeting
957 boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
....
972 if (realStartActivityLocked(hr, app, true, true)) {
973 didSomething = true;
974 }
....
984 if (!didSomething) {
985 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
986 }
987 return didSomething;
988 }
1325 final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
1326 boolean andResume, boolean checkConfig) throws RemoteException {
1327 //等到所有的onPause()方法执行结束才会去启动新的Activity
1328 if (!allPausedActivitiesComplete()) {
1335 return false;
1336 }
....
1466 //调用ApplicationThread的scheduleLaunchActivity用于启动一个Activity
1467 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
1468 System.identityHashCode(r), r.info,
1469 // TODO: Have this take the merged configuration instead of separate global and
1470 // override configs.
1471 mergedConfiguration.getGlobalConfiguration(),
1472 mergedConfiguration.getOverrideConfiguration(), r.compat,
1473 r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
1474 r.persistentState, results, newIntents, !andResume,
1475 mService.isNextTransitionForward(), profilerInfo);
....
1548
1549 return true;
1550 }
Step 6.2, ApplicationThread.scheduleLaunchActivity()
748 // we use token to identify this activity without having to send the
749 // activity itself back to the activity manager. (matters more with ipc)
750 @Override
751 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
752 ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
753 CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
754 int procState, Bundle state, PersistableBundle persistentState,
755 List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
756 boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
757
....
783 sendMessage(H.LAUNCH_ACTIVITY, r);
784 }
Step 7.2, ActivityThread.H receives
LAUNCH_ACTIVITY
1584 public void handleMessage(Message msg) {
1585 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
1586 switch (msg.what) {
1587 case LAUNCH_ACTIVITY: {
1588 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
1589 final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
1590
1591 r.packageInfo = getPackageInfoNoCheck(
1592 r.activityInfo.applicationInfo, r.compatInfo);
1593 handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
1594 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1595 } break;
Step 8.2, handleLaunchActivity
2872 private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
2874 //如果我们在进入后台后准备gc,那么我们回到活动状态,所以跳过它。
....
2883 //确保我们正在运行最新的配置。
2889 // 创建活动之前进行初始化
2890 WindowManagerGlobal.initialize();
2891
2892 Activity a = performLaunchActivity(r, customIntent);
2893
// 一些关于onResume还是finish的判断
2894 if (a != null) {
2895 r.createdConfig = new Configuration(mConfiguration);
2896 reportSizeConfigurations(r);
2897 Bundle oldState = r.state;
// 这里会调用到 ActivityClientRecord.activity.performResume(),判断是否 onResume调用
2898 handleResumeActivity(r.token, false, r.isForward,
2899 !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
2900
2901 if (!r.activity.mFinished && r.startsNotResumed) {
2902 // The activity manager actually wants this one to start out paused, because it
2903 // needs to be visible but isn't in the foreground. We accomplish this by going
2904 // through the normal startup (because activities expect to go through onResume()
2905 // the first time they run, before their window is displayed), and then pausing it.
2906 // However, in this case we do -not- need to do the full pause cycle (of freezing
2907 // and such) because the activity manager assumes it can just retain the current
2908 // state it has.
2909 performPauseActivityIfNeeded(r, reason);
2910
2911 // We need to keep around the original state, in case we need to be created again.
2912 // But we only do this for pre-Honeycomb apps, which always save their state when
2913 // pausing, so we can not have them save their state when restarting from a paused
2914 // state. For HC and later, we want to (and can) let the state be saved as the
2915 // normal part of stopping the activity.
2916 if (r.isPreHoneycomb()) {
2917 r.state = oldState;
2918 }
2919 }
2920 } else {
2921 // If there was an error, for any reason, tell the activity manager to stop us.
2922 try {
2923 ActivityManager.getService()
2924 .finishActivity(r.token, Activity.RESULT_CANCELED, null,
2925 Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
2926 } catch (RemoteException ex) {
2927 throw ex.rethrowFromSystemServer();
2928 }
2929 }
2930 }
performLaunchActivity
2683 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
2684 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
2685
....
2703
2704 ContextImpl appContext = createBaseContextForActivity(r);
2705 Activity activity = null;
2706 try {
//通过Instrumentation反射获取Activity实例
2707 java.lang.ClassLoader cl = appContext.getClassLoader();
2708 activity = mInstrumentation.newActivity(
2709 cl, component.getClassName(), r.intent);
2710 StrictMode.incrementExpectedActivityCount(activity.getClass());
2711 r.intent.setExtrasClassLoader(cl);
2712 r.intent.prepareToEnterProcess();
2713 if (r.state != null) {
2714 r.state.setClassLoader(cl);
2715 }
2716 } catch (Exception e) {
2717 if (!mInstrumentation.onException(activity, e)) {
2718 throw new RuntimeException(
2719 "Unable to instantiate activity " + component
2720 + ": " + e.toString(), e);
2721 }
2722 }
2723
2724 try {
//如果是多进程就创建,不是多进程就不创建
2725 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
2726
....
//回调activity的attach方法
2749 appContext.setOuterContext(activity);
2750 activity.attach(appContext, this, getInstrumentation(), r.token,
2751 r.ident, app, r.intent, r.activityInfo, title, r.parent,
2752 r.embeddedID, r.lastNonConfigurationInstances, config,
2753 r.referrer, r.voiceInteractor, window, r.configCallback);
2754
2755 if (customIntent != null) {
2756 activity.mIntent = customIntent;
2757 }
....
//设置主题
2761 int theme = r.activityInfo.getThemeResource();
2762 if (theme != 0) {
2763 activity.setTheme(theme);
2764 }
2765
//通过Instrumentation来回调activity的onCreate()方法
2766 activity.mCalled = false;
2767 if (r.isPersistable()) {
2768 mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
2769 } else {
2770 mInstrumentation.callActivityOnCreate(activity, r.state);
2771 }
2772 if (!activity.mCalled) {
2773 throw new SuperNotCalledException(
2774 "Activity " + r.intent.getComponent().toShortString() +
2775 " did not call through to super.onCreate()");
2776 }
2777 r.activity = activity;
2778 r.stopped = true;
//start
2779 if (!r.activity.mFinished) {
2780 activity.performStart();
2781 r.stopped = false;
2782 }
//RestoreInstanceState
2783 if (!r.activity.mFinished) {
2784 if (r.isPersistable()) {
2785 if (r.state != null || r.persistentState != null) {
2786 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
2787 r.persistentState);
2788 }
2789 } else if (r.state != null) {
2790 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
2791 }
2792 }
//OnPostCreate
2793 if (!r.activity.mFinished) {
2794 activity.mCalled = false;
2795 if (r.isPersistable()) {
2796 mInstrumentation.callActivityOnPostCreate(activity, r.state,
2797 r.persistentState);
2798 } else {
2799 mInstrumentation.callActivityOnPostCreate(activity, r.state);
2800 }
2801 if (!activity.mCalled) {
2802 throw new SuperNotCalledException(
2803 "Activity " + r.intent.getComponent().toShortString() +
2804 " did not call through to super.onPostCreate()");
2805 }
2806 }
2807 }
2808 r.paused = true;
2809 //加入mActivities Map统一管理
2810 mActivities.put(r.token, r);
2811
2812 } catch (SuperNotCalledException e) {
2813 throw e;
2814
2815 } catch (Exception e) {
2816 if (!mInstrumentation.onException(activity, e)) {
2817 throw new RuntimeException(
2818 "Unable to start activity " + component
2819 + ": " + e.toString(), e);
2820 }
2821 }
2822
2823 return activity;
2824 }
3. API
3.1、ActivityThread
http://aospxref.com/android-14.0.0_r2/xref/frameworks/base/core/java/android/app/ActivityThread.java
Here are some methods of the ActivityThread
class in Android 8:
-
main(): The main entry point of the application process, used to initialize the global state of the application, including creating
Application
instances and starting the main application process. Activity, processing message queue, etc. -
attach(): Attach
ActivityThread
to the application's process for initialization and life cycle management of the application. -
bindApplication(): Bind the application to the application process, including creating the
Application
instance and calling itsonCreate
method , start the main Activity of the application. -
schedulePauseActivity(): Requests to pause the life cycle of the specified Activity.
-
scheduleStopActivity(): Requests to stop the life cycle of the specified Activity.
-
scheduleWindowVisibility(): Handles changes in window visibility.
-
scheduleLaunchActivity(): Requests to start a new Activity.
-
scheduleReceiver(): Handles the registration and scheduling of broadcast receivers.
-
scheduleCreateService(): Request to create a service.
-
scheduleBindService(): Request binding service.
-
scheduleUnbindService(): Request to unbind service.
-
scheduleServiceArgs(): Pass parameters to the service.
-
scheduleStopService(): Request to stop the service.
-
scheduleRegisteredReceiver(): Handles registered broadcast receivers.
-
scheduleLowMemory(): Handles the situation of insufficient system memory.
-
dispatchPackageBroadcast(): Dispatch the broadcast of the application package.
-
dumpService(): Output service information.
-
scheduleCrash(): The requesting application process crashed.
-
dumpHeap(): Output heap dump information.
-
attachAgent(): Attached agent.
-
setSchedulingGroup(): Set the scheduling group.
-
requestAssistContextExtras(): Request auxiliary context information.
-
updatePackageCompatibilityInfo(): Update the compatibility information of the application package.
-
scheduleTrimMemory(): Request memory trimming.
-
scheduleOnNewActivityOptions(): Notifies new Activity options.
These methods are used to manage the life cycle of the application and handle messages and events to ensure that the application can start, run and respond to user operations normally. Note that these methods may change between Android versions, and there may be other private methods that implement new features in different versions. If you need to know the ActivityThread
method for a specific version of Android, check the Android source code or official documentation for that version.
3.2、ApplicationThread
Here are some methods of the ApplicationThread
class in Android 8:
-
bindApplication(): Used to bind the application to the application process. This method is responsible for creating an
Application
instance of the application and calling itsonCreate()
method, as well as starting the application's main Activity. -
schedulePauseActivity(): Requests to pause the life cycle of the specified Activity.
-
scheduleStopActivity(): Requests to stop the life cycle of the specified Activity.
-
scheduleWindowVisibility(): Handles changes in window visibility.
-
scheduleResumeActivity(): Requests to resume the life cycle of the specified Activity.
-
scheduleSendResult(): used to send the results of Activity.
-
scheduleLaunchActivity(): Requests to start a new Activity.
-
scheduleCreateService(): Request to create a service.
-
scheduleBindService(): Request binding service.
-
scheduleUnbindService(): Request to unbind service.
-
scheduleServiceArgs(): Pass parameters to the service.
-
scheduleStopService(): Request to stop the service.
-
scheduleLowMemory(): Handles the situation of insufficient system memory.
-
scheduleCrash(): The requesting application process crashed.
-
dumpHeap(): Used to output heap dump information.
-
dumpActivity(): used to output Activity information.
-
scheduleRegisteredReceiver(): Handles registered broadcast receivers.
-
scheduleCreateBackupAgent(): Used to request the creation of a backup agent, usually called when the application needs to back up and restore data.
-
scheduleDestroyBackupAgent(): Used to request the destruction of the backup agent, usually called after the backup operation is completed.
-
scheduleSuicide(): Requests the application process to commit suicide.
-
scheduleConfigurationChanged(): Used to handle configuration changes.
-
scheduleSleeping(): Used to handle the sleep state of the application process.
-
dispatchPackageBroadcast(): Dispatch the broadcast of the application package.
-
requestThumbnail(): Request to obtain the thumbnail of Activity.
-
profilerControl(): used for performance profiling control.
These methods are used to manage the life cycle of the application and handle messages and events to ensure that the application can start, run and respond to user operations normally. Note that these methods may change between Android versions, and there may be other private methods that implement new features in different versions. If you need to know the ApplicationThread
method for a specific version of Android, check the Android source code or official documentation for that version.
3.3、ActivityManagerService
ActivityManagerService:
http://aospxref.com/android-8.0.0_r36/xref/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java#attachApplicationLocked
3.4、ActivityStackSupervisor
ActivityStackSupervisor:
http://aospxref.com/android-8.0.0_r36/xref/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
Reference address
Most of the article is reproduced from:
https://www.jianshu.com/p/643aa7c8e3dd
https://blog.csdn.net/sinat_31057219/article/details/132452043
https://blog.51cto.com/u_16213631/7298774
Detailed analysis of the startup process!!
https://blog.csdn.net/weixin_43093006/article/details/128699383