Skip to content

Activity

Posted on:March 4, 2021 at 20:49:29 GMT+8

Android 11 API 30

源码注释

An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View). While activities are often presented to the user as full-screen windows, they can also be used in other ways: as floating windows (via a theme with R.attr.windowIsFloating set), Multi-Window mode or embedded into other windows. There are two methods almost all subclasses of Activity will implement:

Activity 是用户可以做的单个的、获得关注的东西。几乎所有的 Activity 都与用户交互,所以 Activity 类为你创建 window,让你可以把 UI 通过 setContentView() 放在 window 里。尽管 Activity 经常是全屏地展现给用户,TA 们也可以通过其它方式使用:作为悬浮窗口(通过将主题设置为 R.attr.windowIsFloationg)、作为多窗口模式或是嵌套在其它窗口中。有两个方法几乎 Acitivity 的所有子类都会实现:

onCreate(Bundle) 是你初始化你的 Activity 的地方。最重要的是,在这你将调用 setContentView with 一个布局资源来定义你的 UI,和使用 findViewById 取得你需要的 UI 中的 widget,以用编程的方式与其交互。

onPause() 是你处理用户暂停与 Activity 的活跃的交互的地方。任何用户造成的改变应该在此时间点提交(经常是 ContentProvider 掌握数据)。在这个状态,Activity 仍然在屏幕上可见。

To be of use with Context.startActivity(), all activity classes must have a corresponding <activity> declaration in their package’s AndroidManifest.xml.

为了使用 Context.startActivity(),所有的 Activity 类必须在所在的 package 的 AndroidManifest.xml 中有对应的 <activity> 声明。

Topics covered here:

话题包括:

  1. Fragments
  2. Activity Lifecycle
  3. Configuration Changes
  4. Starting Activities and Getting Results
  5. Saving Persistent State
  6. Permissions
  7. Process Lifecycle

Developer Guides

The Activity class is an important part of an application’s overall lifecycle, and the way activities are launched and put together is a fundamental part of the platform’s application model. For a detailed perspective on the structure of an Android application and how activities behave, please read the Application Fundamentals and Tasks and Back Stack developer guides.

You can also find a detailed discussion about how to create activities in the Activities developer guide.

Fragments

The FragmentActivity subclass can make use of the Fragment class to better modularize their code, build more sophisticated user interfaces for larger screens, and help scale their application between small and large screens.

FragmentActivity 子类可以让 Fragment 类更好地模块化 TA 们的代码,为大屏构建更复杂的 UI,帮助 TA 们的应用在大的小的屏幕上缩放。

For more information about using fragments, read the Fragments developer guide.

Activity Lifecycle

Activities in the system are managed as activity stacks. When a new activity is started, it is usually placed on the top of the current stack and becomes the running activity — the previous activity always remains below it in the stack, and will not come to the foreground again until the new activity exits. There can be one or multiple activity stacks visible on screen.

可以有一个或多个 Activity 栈在屏幕上可见。

An activity has essentially four states:

The following diagram shows the important state paths of an Activity. The square rectangles represent callback methods you can implement to perform operations when the Activity moves between states. The colored ovals are major states the Activity can be in.

State diagram for an Android Activity Lifecycle.

There are three key loops you may be interested in monitoring within your activity:

The entire lifecycle of an activity is defined by the following Activity methods. All of these are hooks that you can override to do appropriate work when the activity changes state. All activities will implement onCreate(Bundle) to do their initial setup; many will also implement onPause() to commit changes to data and prepare to pause interacting with the user, and onStop() to handle no longer being visible on screen. You should always call up to your superclass when implementing these methods.

 public class Activity extends ApplicationContext {
     protected void onCreate(Bundle savedInstanceState);

     protected void onStart();

     protected void onRestart();

     protected void onResume();

     protected void onPause();

     protected void onStop();

     protected void onDestroy();
 }

In general the movement through an activity’s lifecycle looks like this:

MethodDescriptionKillable?Next
onCreate()Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity’s previously frozen state, if there was one. Always followed by onStart().
这个方法也提供一个 Bundle,包含 Activity 之前冻结的动态,如果有。
NoonStart()
onRestart()Called after your activity has been stopped, prior to it being started again. Always followed by onStart()
在 Activity 停止后,在 TA 重启之前。总是在 onStart() 之后。
NoonStart()
onStart()Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
当 Activity 变得可见之时调用。如果 Activity 从后台返回前台, onResume() 会在之后调用。如果变得隐藏,onStop() 会接着调用。
onResume() or onStop()
onResume()Called when the activity will start interacting with the user. At this point your activity is at the top of its activity stack, with user input going to it. Always followed by onPause().
当 Activity 将开始与用户交互时调用。在这个时刻,你的 Activity 在栈顶,用户正在输入。后面总是跟着 onPause()。
NoonPause()
onPause()Called when the activity loses foreground state, is no longer focusable or before transition to stopped/hidden or destroyed state. The activity is still visible to user, so it’s recommended to keep it visually active and continue updating the UI. Implementations of this method must be very quick because the next activity will not be resumed until this method returns. Followed by either onResume() if the activity returns back to the front, or onStop() if it becomes invisible to the user.Pre-Build.VERSION_CODES.HONEYCOMBonResume() or onStop()
onStop()Called when the activity is no longer visible to the user. This may happen either because a new activity is being started on top, an existing one is being brought in front of this one, or this one is being destroyed. This is typically used to stop animations and refreshing the UI, etc. Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.YesonRestart() or onDestroy()
onDestroy()The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called Activity#finish on it), or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.Yesnothing

Note the “Killable” column in the above table — for those methods that are marked as being killable, after that method returns the process hosting the activity may be killed by the system at any time without another line of its code being executed. Because of this, you should use the onPause() method to write any persistent data (such as user edits) to storage. In addition, the method onSaveInstanceState(android.os.Bundle) is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in onCreate(Bundle) if the activity needs to be re-created. See the Process Lifecycle section for more information on how the lifecycle of a process is tied to the activities it is hosting. Note that it is important to save persistent data in onPause() instead of onSaveInstanceState(Bundle) because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.

Be aware that these semantics will change slightly between applications targeting platforms starting with Build.VERSION_CODES.HONEYCOMB vs. those targeting prior platforms. Starting with Honeycomb, an application is not in the killable state until its onStop() has returned. This impacts when onSaveInstanceState(android.os.Bundle) may be called (it may be safely called after onPause()) and allows an application to safely wait until onStop() to save persistent state.

For applications targeting platforms starting with Build.VERSION_CODES.P onSaveInstanceState(android.os.Bundle) will always be called after onStop(), so an application may safely perform fragment transactions in onStop() and will be able to save persistent state later.

For those methods that are not marked as being killable, the activity’s process will not be killed by the system starting from the time the method is called and continuing after it returns. Thus an activity is in the killable state, for example, between after onStop() to the start of onResume(). Keep in mind that under extreme memory pressure the system can kill the application process at any time.

Configuration Changes

If the configuration of the device (as defined by the Resources.Configuration class) changes, then anything displaying a user interface will need to update to match that configuration. Because Activity is the primary mechanism for interacting with the user, it includes special support for handling configuration changes.

如果设备的配置(定义在 Resource.Configuration 类中)改变,任何展示 UI 的东西都需要更新以符合配置。因为 Activity 是与用户交互的主要机制,所以包含处理配置改变的特殊支持。

Unless you specify otherwise, a configuration change (such as a change in screen orientation, language, input devices, etc) will cause your current activity to be destroyed, going through the normal activity lifecycle process of onPause(), onStop(), and onDestroy() as appropriate. If the activity had been in the foreground or visible to the user, once onDestroy() is called in that instance then a new instance of the activity will be created, with whatever savedInstanceState the previous instance had generated from onSaveInstanceState(Bundle).

This is done because any application resource, including layout files, can change based on any configuration value. Thus the only safe way to handle a configuration change is to re-retrieve all resources, including layouts, drawables, and strings. Because activities must already know how to save their state and re-create themselves from that state, this is a convenient way to have an activity restart itself with a new configuration.

In some special cases, you may want to bypass restarting of your activity based on one or more types of configuration changes. This is done with the android:configChanges attribute in its manifest. For any types of configuration changes you say that you handle there, you will receive a call to your current activity’s onConfigurationChanged(Configuration) method instead of being restarted. If a configuration change involves any that you do not handle, however, the activity will still be restarted and onConfigurationChanged(Configuration) will not be called.

在一些特殊情况,你可能想基于一种或多种类型的配置改变来绕过重启你的 Activity。通过 manifest 中的 android:configChanges 做到。对于任何在这里处理的配置改变,将收到对你目前的 Activity 的 onConfigurationChanged(Configuration) 方法调用,而不是重启。如果配置改变包括你没有处理的,Activity 仍会重启且 onConfigurationChanged(Configuration) 不会被调用。

Starting Activities and Getting Results

启动 Activity 和获得结果

The startActivity(Intent) method is used to start a new activity, which will be placed at the top of the activity stack. It takes a single argument, an Intent, which describes the activity to be executed.

startActivity(Intent) 方法被用作启动一个新的 Activity,将会被放在栈顶。方法需要单个 Intent 作为参数,参数描述了要被执行的 Activity。

Sometimes you want to get a result back from an activity when it ends. For example, you may start an activity that lets the user pick a person in a list of contacts; when it ends, it returns the person that was selected. To do this, you call the startActivityForResult(Intent, int) version with a second integer parameter identifying the call. The result will come back through your onActivityResult(int, int, Intent) method.

有时你想在一个 Activity 结束的时候获得返回的结果。 要做到这个,调用 startActivityForResult(Intent, int) 方法,第二个 int 参数辨别调用。结果会通过你的 onActivityResult(int, int, Intent) 方法返回。

When an activity exits, it can call setResult(int) to return data back to its parent. It must always supply a result code, which can be the standard results RESULT_CANCELED, RESULT_OK, or any custom values starting at RESULT_FIRST_USER. In addition, it can optionally return back an Intent containing any additional data it wants. All of this information appears back on the parent’s Activity.onActivityResult(), along with the integer identifier it originally supplied.

当一个 Activity 退出时,TA 可以调用 setResult(int) 来返回数据给父 Activity。方法必须提供一个 result code,可以是标准的结果 RESULT_CANCELED,RESULT_OK,或是任何自定义的值,从 RESULT_FIREST_USER 开始。此外,还可以选择返回一个包含任何想要的数据的 Intent。所有的这些信息在父 Activity.onActivityResut() 方法中出现,随着 TA 初始提供的 integer 标识符。

If a child activity fails for any reason (such as crashing), the parent activity will receive a result with the code RESULT_CANCELED.

如果子 Activity 因为某种原因失败了(例如崩溃),父 Activity 将收到随着 RESULT_CANCELED 的结果。

 public class MyActivity extends Activity {
     ...

     static final int PICK_CONTACT_REQUEST = 0;

     public boolean onKeyDown(int keyCode, KeyEvent event) {
         if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
             // When the user center presses, let them pick a contact.
             startActivityForResult(
                 new Intent(Intent.ACTION_PICK,
                 new Uri("content://contacts")),
                 PICK_CONTACT_REQUEST);
            return true;
         }
         return false;
     }

     protected void onActivityResult(int requestCode, int resultCode,
             Intent data) {
         if (requestCode == PICK_CONTACT_REQUEST) {
             if (resultCode == RESULT_OK) {
                 // A contact was picked.  Here we will just display it
                 // to the user.
                 startActivity(new Intent(Intent.ACTION_VIEW, data));
             }
         }
     }
 }

Saving Persistent State

There are generally two kinds of persistent state that an activity will deal with: shared document-like data (typically stored in a SQLite database using a content provider) and internal state such as user preferences.

For content provider data, we suggest that activities use an “edit in place” user model. That is, any edits a user makes are effectively made immediately without requiring an additional confirmation step. Supporting this model is generally a simple matter of following two rules:

This model is designed to prevent data loss when a user is navigating between activities, and allows the system to safely kill an activity (because system resources are needed somewhere else) at any time after it has been stopped (or paused on platform versions before Build.VERSION_CODES.HONEYCOMB). Note this implies that the user pressing BACK from your activity does not mean “cancel” — it means to leave the activity with its current contents saved away. Canceling edits in an activity must be provided through some other mechanism, such as an explicit “revert” or “undo” option.

See the content package for more information about content providers. These are a key aspect of how different activities invoke and propagate data between themselves.

The Activity class also provides an API for managing internal persistent state associated with an activity. This can be used, for example, to remember the user’s preferred initial display in a calendar (day view or week view) or the user’s default home page in a web browser.

Activity persistent state is managed with the method getPreferences(int), allowing you to retrieve and modify a set of name/value pairs associated with the activity. To use preferences that are shared across multiple application components (activities, receivers, services, providers), you can use the underlying Context.getSharedPreferences() method to retrieve a preferences object stored under a specific name. (Note that it is not possible to share settings data across application packages — for that you will need a content provider.)

Here is an excerpt from a calendar activity that stores the user’s preferred view mode in its persistent settings:

 public class CalendarActivity extends Activity {
     ...

     static final int DAY_VIEW_MODE = 0;
     static final int WEEK_VIEW_MODE = 1;

     private SharedPreferences mPrefs;
     private int mCurViewMode;

     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);

         SharedPreferences mPrefs = getSharedPreferences();
         mCurViewMode = mPrefs.getInt("view_mode", DAY_VIEW_MODE);
     }

     protected void onPause() {
         super.onPause();

         SharedPreferences.Editor ed = mPrefs.edit();
         ed.putInt("view_mode", mCurViewMode);
         ed.commit();
     }
 }

Permissions

The ability to start a particular Activity can be enforced when it is declared in its manifest’s <activity> tag. By doing so, other applications will need to declare a corresponding <uses-permission> element in their own manifest to be able to start that activity.

When starting an Activity you can set Intent.FLAG_GRANT_READ_URI_PERMISSION and/or Intent.FLAG_GRANT_WRITE_URI_PERMISSION on the Intent. This will grant the Activity access to the specific URIs in the Intent. Access will remain until the Activity has finished (it will remain across the hosting process being killed and other temporary destruction). As of Build.VERSION_CODES.GINGERBREAD, if the Activity was already created and a new Intent is being delivered to onNewIntent(android.content.Intent), any newly granted URI permissions will be added to the existing ones it holds.

See the Security and Permissions document for more information on permissions and security in general.

Process Lifecycle

The Android system attempts to keep an application process around for as long as possible, but eventually will need to remove old processes when memory runs low. As described in Activity Lifecycle, the decision about which process to remove is intimately tied to the state of the user’s interaction with it. In general, there are four states a process can be in based on the activities running in it, listed here in order of importance. The system will kill less important processes (the last ones) before it resorts to killing more important processes (the first ones).

  1. The foreground activity (the activity at the top of the screen that the user is currently interacting with) is considered the most important. Its process will only be killed as a last resort, if it uses more memory than is available on the device. Generally at this point the device has reached a memory paging state, so this is required in order to keep the user interface responsive.
  2. A visible activity (an activity that is visible to the user but not in the foreground, such as one sitting behind a foreground dialog or next to other activities in multi-window mode) is considered extremely important and will not be killed unless that is required to keep the foreground activity running.
  3. A background activity (an activity that is not visible to the user and has been stopped) is no longer critical, so the system may safely kill its process to reclaim memory for other foreground or visible processes. If its process needs to be killed, when the user navigates back to the activity (making it visible on the screen again), its onCreate(Bundle) method will be called with the savedInstanceState it had previously supplied in onSaveInstanceState(Bundle) so that it can restart itself in the same state as the user last left it.
  4. An empty process is one hosting no activities or other application components (such as Service or BroadcastReceiver classes). These are killed very quickly by the system as memory becomes low. For this reason, any background operation you do outside of an activity must be executed in the context of an activity BroadcastReceiver or Service to ensure that the system knows it needs to keep your process around.

Sometimes an Activity may need to do a long-running operation that exists independently of the activity lifecycle itself. An example may be a camera application that allows you to upload a picture to a web site. The upload may take a long time, and the application should allow the user to leave the application while it is executing. To accomplish this, your Activity should start a Service in which the upload takes place. This allows the system to properly prioritize your process (considering it to be more important than other non-visible applications) for the duration of the upload, independent of whether the original activity is paused, stopped, or finished.

startActivity(Intent)

Activity#startActivity(Intent)

Activity#startActivity(Intent, Bundle)

Activity#startActivityForResult(Intent, int)

Activity#startActivityForResult(Intent, int, Bundle)

Instrumentation#execStartActivity(Context, IBinder, IBinder, Activity, Intent, int, Bundle)

这里调用 ActivityTaskManager.getService().startActivity() 接着启动 Activity。getService() 返回了一个实现了 IActivityTaskManager (由 IActivityTaskManager.aidl 定义)的对象,ActivityTaskManagerService 继承了 IActivityTaskManager.Stub。

ActivityTaskManagerService 是管理 Activity 和 TA 的容器(task, stacks, displays, …)的 system service。

ActivityTaskManagerService#startActivity

ActivityTaskManagerService#startActivityAsUser

这里有:

// TODO: Switch to user app stacks here.
return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
        .setCaller(caller)
        .setCallingPackage(callingPackage)
        .setCallingFeatureId(callingFeatureId)
        .setResolvedType(resolvedType)
        .setResultTo(resultTo)
        .setResultWho(resultWho)
        .setRequestCode(requestCode)
        .setStartFlags(startFlags)
        .setProfilerInfo(profilerInfo)
        .setActivityOptions(bOptions)
        .setUserId(userId)
        .execute();

getActivityStartController 得到的是 ActivityStartController。再 obtainStarter 得到的是 ActivityStarter。ActivityStarter 是用于解释如何启动一个 Activity,然后启动 Activity 的。

ActivityStarter#execute

executeRequest(mRequest) 执行一个 Activity 启动请求,启动一个 Activity 的启动旅程。在这里开始一些初步的检查。正常的 Activity 启动流程将从 startActivityUchecked 到 startActivityInner。

在方法的最后又调用了 startActivityUnchecked。调用这个方法就意味着大部分的初步检查已经完成且调用者已经确认了有必要的权限。这里同时确保了如果启动不成功会移除正在启动的 Activity。

startActivityInner 启动一个 Activity,确定 Activity 是否应该添加到现有 task 的栈顶或是传一个 intent 给已有的 Activity。并且操作 Activity task 成要求的或有效的 stack/display。

方法里重点有一个:

mRootWindowContainer.resumeFocusedStacksTopActivities(
        mTargetStack, mStartActivity, mOptions);

RootWindowContainer#resumeFocusedStacksTopActivities 里调用了

ActivityStack#resumeTopActivityUncheckedLocked 确保栈顶的 Activity 是 resumed。

resumeTopActivityInnerLocked 主要负责上一个 Activity 的 pause 和下一个 Activity 的 resume 一系列操作。

ActivityStack#startPausingLocked pause 目前 resume 的 Activity。

mAtmService.getLifecycleManager().scheduleTransaction(prev.app.getThread(),
        prev.appToken, PauseActivityItem.obtain(prev.finishing, userLeaving,
                prev.configChangeFlags, pauseImmediately));

mAtmService.getLifecycleManager() 返回的是 ClientLifecycleManager 的实例。

ClientLifecycleManager 该类能组合多个生命周期请求和/或回调,并将 TA 们作为单个事务执行。

ClientLifecycleManager#scheduleTransaction

void scheduleTransaction(@NonNull IApplicationThread client, @NonNull IBinder activityToken,
		@NonNull ActivityLifecycleItem stateRequest) throws RemoteException {
	final ClientTransaction clientTransaction = transactionWithState(client, activityToken,
			stateRequest);
	scheduleTransaction(clientTransaction);
}
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
	final IApplicationThread client = transaction.getClient();
	transaction.schedule();
	if (!(client instanceof Binder)) {
		// If client is not an instance of Binder - it's a remote call and at this point it is
		// safe to recycle the object. All objects used for local calls will be recycled after
		// the transaction is executed on client in ActivityThread.
		transaction.recycle();
	}
}

ClientTransaction#schedule

ClientTransaction:保存一系列消息的容器,这些消息可能被发送到客户端,包括一个回调列表和一个最终的生命周期状态。

ActivityLifecycleItem:用以请求 Activity 应该到达的生命周期状态。继承自 ClientTransctionItem,主要的子类有 DestoryActivityItem、PauseActivityItem、StopActivityItem、ResumeActivityItem 等。将每一个生命周期的节点单独封装,虽然在代码层次和阅读上趋于复杂化了,但是更方便于对每一个生命周期进行单独维护而不必影响其他代码。

public void schedule() throws RemoteException {
	mClient.scheduleTransaction(this);
}

mClient 是 IApplicationThread 类型。

IApplicationThread:是系统进程持有的 app 进程中 ApplicationThread 的 Binder 代理对象。系统进程通过 ProcessRecord.IApplicationThread 调用 app 进程相关方法。

ApplicationThread:ActivityThread 的内部类。AMS 通过 binder 代理调用到 ApplicationThread 中的方法后,通过主线程(ActivityThread 中的 main 方法)中开启的 handler 消息轮询来通知主线程调用相关方法。主线程的相关生命周期方法的具体实现会委托给 Instrumentation 类实现,在 Instrumentation 类中,会调用具体组件的相关生命周期方法。

ApplicationThread#scheduleTransaction

@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
	ActivityThread.this.scheduleTransaction(transaction);
}

ActivityThread 的父类 ClientTransactionHandler:

ClientTransactionHandler#scheduleTransaction

    /** Prepare and schedule transaction for execution. */
    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }

sendMessage 在父类中是抽象方法。

ActivityThread#H#handleMessage

case EXECUTE_TRANSACTION:
	final ClientTransaction transaction = (ClientTransaction) msg.obj;
	mTransactionExecutor.execute(transaction);
	if (isSystem()) {
		// Client transactions inside system process are recycled on the client side
		// instead of ClientLifecycleManager to avoid being cleared before this
		// message is handled.
		transaction.recycle();
	}
	// TODO(lifecycler): Recycle locally scheduled transactions.
	break;

mTransactionExecutorTransactionExecutor的实例。

TransactionExecutor#execute中调用executeCallbacksexecuteCallbacks中调用TransactionExecutor#cycleToPathcycleToPath中调用TransactionExecutor#performLifecycleSequence

    /** Transition the client through previously initialized state sequence. */
    private void performLifecycleSequence(ActivityClientRecord r, IntArray path,
            ClientTransaction transaction) {
        final int size = path.size();
        for (int i = 0, state; i < size; i++) {
            state = path.get(i);
            if (DEBUG_RESOLVER) {
                Slog.d(TAG, tId(transaction) + "Transitioning activity: "
                        + getShortActivityName(r.token, mTransactionHandler)
                        + " to state: " + getStateName(state));
            }
            switch (state) {
                case ON_CREATE:
                    mTransactionHandler.handleLaunchActivity(r, mPendingActions,
                            null /* customIntent */);
                    break;
                case ON_START:
                    mTransactionHandler.handleStartActivity(r.token, mPendingActions);
                    break;
                case ON_RESUME:
                    mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
                            r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
                    break;
                case ON_PAUSE:
                    mTransactionHandler.handlePauseActivity(r.token, false /* finished */,
                            false /* userLeaving */, 0 /* configChanges */, mPendingActions,
                            "LIFECYCLER_PAUSE_ACTIVITY");
                    break;
                case ON_STOP:
                    mTransactionHandler.handleStopActivity(r.token, 0 /* configChanges */,
                            mPendingActions, false /* finalStateRequest */,
                            "LIFECYCLER_STOP_ACTIVITY");
                    break;
                case ON_DESTROY:
                    mTransactionHandler.handleDestroyActivity(r.token, false /* finishing */,
                            0 /* configChanges */, false /* getNonConfigInstance */,
                            "performLifecycleSequence. cycling to:" + path.get(size - 1));
                    break;
                case ON_RESTART:
                    mTransactionHandler.performRestartActivity(r.token, false /* start */);
                    break;
                default:
                    throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
            }
        }
    }

mTransactionHandler是类ClientTransactionHandler的实例对象,ClientTransactionHandler中的handleLaunchActivity是一个抽象方法,ActivityThread 作为其子类,实现了他的handleLaunchActivity方法,在ActivityThread#handleLaunchActivity方法中调用了ActivityThread#performLaunchActivity

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
	>>>
	Activity activity = null;
	try {
		java.lang.ClassLoader cl = appContext.getClassLoader();
		activity = mInstrumentation.newActivity(
				cl, component.getClassName(), r.intent);
		StrictMode.incrementExpectedActivityCount(activity.getClass());
		r.intent.setExtrasClassLoader(cl);
		r.intent.prepareToEnterProcess();
		if (r.state != null) {
			r.state.setClassLoader(cl);
		}
	} catch (Exception e) {
		>>>
	}
	>>>
	if (r.isPersistable()) {
		mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
	} else {
		mInstrumentation.callActivityOnCreate(activity, r.state);
	}
	>>>
}

第一段是 Activity 的创建,第二段是 onCreate 方法的执行。

Instrumentation#newActivity

public Activity newActivity(ClassLoader cl, String className,
		Intent intent)
		throws InstantiationException, IllegalAccessException,
		ClassNotFoundException {
	String pkg = intent != null && intent.getComponent() != null
			? intent.getComponent().getPackageName() : null;
	return getFactory(pkg).instantiateActivity(cl, className, intent);
}

AppComponentFactory#instantiateActivity

public @NonNull Activity instantiateActivity(@NonNull ClassLoader cl, @NonNull String className,
		@Nullable Intent intent)
		throws InstantiationException, IllegalAccessException, ClassNotFoundException {
	return (Activity) cl.loadClass(className).newInstance();
}

由此可看出,Activity是通过类加载器去创建的实例。

Instrumentation#callActivityOnCreate

public void callActivityOnCreate(Activity activity, Bundle icicle) {
	prePerformCreate(activity);
	activity.performCreate(icicle);
	postPerformCreate(activity);
}

Activity#performCreate

@UnsupportedAppUsage
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
	dispatchActivityPreCreated(icicle);
	mCanEnterPictureInPicture = true;
	restoreHasCurrentPermissionRequest(icicle);
	if (persistentState != null) {
		onCreate(icicle, persistentState);
	} else {
		onCreate(icicle);
	}
	writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate");
	mActivityTransitionState.readState(icicle);

	mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
			com.android.internal.R.styleable.Window_windowNoDisplay, false);
	mFragments.dispatchActivityCreated();
	mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
	dispatchActivityPostCreated(icicle);
}

至此,就能看到我们所熟悉的onCreate方法了。

参考

源码

Android11中Activity的启动流程—从startActivity到onCreate_yu749942362的专栏-CSDN博客

深入研究源码:Activity启动流程分析