frameworks 之 AMS与ActivityThread交互

frameworks 之 AMS与ActivityThread交互

  • [1. 类关系](#1. 类关系)
  • [2. 流程](#2. 流程)
    • [2.1 AMS流程](#2.1 AMS流程)
    • [2.1 ActivityThread流程](#2.1 ActivityThread流程)
  • [3. 堆栈](#3. 堆栈)

讲解AMS 如何和 ActivityThread 生命周期调用流程
涉及到的类如下

  • frameworks/base/core/java/android/app/servertransaction/ResumeActivityItem.java
  • frameworks/base/core/java/android/app/Activity.java
  • frameworks/base/core/java/android/app/ActivityThread.java
  • frameworks/base/services/core/java/com/android/server/wm/ActivityTaskSupervisor.java
  • frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java
  • frameworks/base/core/java/android/app/ClientTransactionHandler.java

1. 类关系

  1. Transaction Item** 以及其子类都为 具体执行的对象
  2. ClientTransaction 作为 AMS 和 ActivityThread 交互的对象 ,里面包含 ActivityLifecycleItemmLifecycleStateRequest 和 List<ClientTransactionItem > mActivityCallbacks 成员变量。
  3. ActivityThread 继承自 ClientTransactionHandler ,里面包含了内部类 ApplicationThread 该类实现了 IApplicationThread.AIDL 方法。当服务端调用该AIDL方法执行app逻辑, 该内容类又会调用 ActivityThread 下的方法,部分方法实现 在 ClientTransactionHandler 中
java 复制代码
		@Override
        public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        	//在父类 ClientTransactionHandler
            ActivityThread.this.scheduleTransaction(transaction);
        }


2. 流程

2.1 AMS流程

startActivity 最后会调用到 realStartActivityLocked 方法。

  1. 构建 ClientTransaction 负责传递给 界面端调用,第一个参数为客户端IApplicationThread AIDL传递给变量mClient
  2. 通过 addCallback添加对应的执行对象
  3. // 将 生命周期要执行的状态 lifecycleItem 传递给对应的 mLifecycleStateRequest 属性
  4. 调用 scheduleTransaction 方法,里面会调用 clientTransaction 的schedule 方法,schedule方法又会调用 mClient 的scheduleTransaction,这时候调用到客户端
java 复制代码
				// 构建 ClientTransaction 负责传递给 界面端调用,第一个参数为客户端IApplicationThread AIDL传递给变量mClient
                final ClientTransaction clientTransaction = ClientTransaction.obtain(
                        proc.getThread(), r.appToken);

                final boolean isTransitionForward = r.isTransitionForward();
                // 添加对应执行的LaunchActivityItem对象,用于给客户端执行
                clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                        System.identityHashCode(r), r.info,
                        // TODO: Have this take the merged configuration instead of separate global
                        // and override configs.
                        mergedConfiguration.getGlobalConfiguration(),
                        mergedConfiguration.getOverrideConfiguration(), r.compat,
                        r.getFilteredReferrer(r.launchedFromPackage), task.voiceInteractor,
                        proc.getReportedProcState(), r.getSavedState(), r.getPersistentSavedState(),
                        results, newIntents, r.takeOptions(), isTransitionForward,
                        proc.createProfilerInfoIfNeeded(), r.assistToken, activityClientController,
                        r.createFixedRotationAdjustmentsIfNeeded(), r.shareableActivityToken,
                        r.getLaunchedFromBubble()));

                // Set desired final state.
                final ActivityLifecycleItem lifecycleItem;
                // 设置对应的状态
                if (andResume) {
                    lifecycleItem = ResumeActivityItem.obtain(isTransitionForward);
                } else {
                    lifecycleItem = PauseActivityItem.obtain();
                }
                // 将 生命周期要执行的状态 lifecycleItem 传递给对应的 mLifecycleStateRequest 属性
                clientTransaction.setLifecycleStateRequest(lifecycleItem);
                // Schedule transaction.
                // 里面会调用 clientTransaction 的schedule 方法,schedule方法又会调用 mClient 的scheduleTransaction
                mService.getLifecycleManager().scheduleTransaction(clientTransaction);
java 复制代码
	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();
        }
    }
	public void schedule() throws RemoteException {
        mClient.scheduleTransaction(this);
    }

2.1 ActivityThread流程

调用了 scheduleTransaction aidl 方法后,就到了 客户端ApplicationThread 执行的方法, 该方法又会调用 scheduleTransaction ,该方法在 ClientTransactionHandler

java 复制代码
 private class ApplicationThread extends IApplicationThread.Stub {
		@Override
        public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
            // 在父类 ClientTransactionHandler
            ActivityThread.this.scheduleTransaction(transaction);
        }
}

查看 ClientTransactionHandler 的 scheduleTransaction 方法。

  1. 执行对应的 preExecute 并将对应的 ActvityThread传递进去
  2. 发送了对应 handler 消息,该消息的接收在 ActvityThread
java 复制代码
void scheduleTransaction(ClientTransaction transaction) {
        // 执行对应的 preExecute并将对应的 ActvityThread传递进去
        transaction.preExecute(this);
        // 发送消息
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }

收到消息后,执行对应的 TransactionExecutor 的 execute 方法,并和咨询

java 复制代码
case EXECUTE_TRANSACTION:
                    // 该回调在其父类触发 scheduleTransaction 发送消息
                    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;

该方法 会通过 executeCallbacks, executeLifecycleState 依次调用 服务端赋值给对应的执行实现类 。

java 复制代码
public void execute(ClientTransaction transaction) {
        ...
        executeCallbacks(transaction);
        // 调用对应的生命周期回调
        executeLifecycleState(transaction);
        mPendingActions.clear();
        if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
    }

onResume 对应的是 executeLifecycleState 方法,该方法会又会调用 对应 实现类的 **execute 和 postExecute ** 方法。从服务端知道 onResume 实现类为 ResumeActivityItem

java 复制代码
private void executeLifecycleState(ClientTransaction transaction) {
        ....
        // Execute the final transition with proper parameters.
        lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
        lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
    }

ResumeActivityItem 的 execute 会执行 ActivityThread 的 handleResumeActivi ty 方法,开始进行对应 activity的 onResume 回调

java 复制代码
	@Override
    public void execute(ClientTransactionHandler client, ActivityClientRecord r,
            PendingTransactionActions pendingActions) {
        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
        // 执行 ActivityThread 的 handleResumeActivity
        client.handleResumeActivity(r, true /* finalStateRequest */, mIsForward,
                "RESUME_ACTIVITY");
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }

handleResumeActivity 方法又会调用对应的 performResumeActivity方法,这样就开始了 onResume回调的触发

java 复制代码
@Override
    public void handleResumeActivity(ActivityClientRecord r, boolean finalStateRequest,
            boolean isForward, 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;

        // TODO Push resumeArgs into the activity for consideration
        // skip below steps for double-resume and r.mFinish = true case.
        if (!performResumeActivity(r, finalStateRequest, reason)) {
            return;
        }
        ...
    }

3. 堆栈

追踪Activity 生命周期调用 如 onResume 可以在 Activity 添加堆栈

java 复制代码
01-16 06:26:45.387  1265  1265 E traceResume: traceResume
01-16 06:26:45.387  1265  1265 E traceResume: java.lang.NullPointerException
01-16 06:26:45.387  1265  1265 E traceResume: 	at android.app.Activity.onResume(Activity.java:1951)
01-16 06:26:45.387  1265  1265 E traceResume: 	at com.android.launcher3.BaseActivity.onResume(BaseActivity.java:182)
01-16 06:26:45.387  1265  1265 E traceResume: 	at com.android.launcher3.BaseDraggingActivity.onResume(BaseDraggingActivity.java:114)
01-16 06:26:45.387  1265  1265 E traceResume: 	at com.android.launcher3.statemanager.StatefulActivity.onResume(StatefulActivity.java:175)
01-16 06:26:45.387  1265  1265 E traceResume: 	at com.android.launcher3.Launcher.onResume(Launcher.java:1133)
01-16 06:26:45.387  1265  1265 E traceResume: 	at com.android.launcher3.BaseQuickstepLauncher.onResume(BaseQuickstepLauncher.java:133)
01-16 06:26:45.387  1265  1265 E traceResume: 	at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1488)
01-16 06:26:45.387  1265  1265 E traceResume: 	at android.app.Activity.performResume(Activity.java:8196)
01-16 06:26:45.387  1265  1265 E traceResume: 	at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4814)
01-16 06:26:45.387  1265  1265 E traceResume: 	at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4857)
01-16 06:26:45.387  1265  1265 E traceResume: 	at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:54)
01-16 06:26:45.387  1265  1265 E traceResume: 	at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45)
01-16 06:26:45.387  1265  1265 E traceResume: 	at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
01-16 06:26:45.387  1265  1265 E traceResume: 	at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
01-16 06:26:45.387  1265  1265 E traceResume: 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2253)
01-16 06:26:45.387  1265  1265 E traceResume: 	at android.os.Handler.dispatchMessage(Handler.java:106)
01-16 06:26:45.387  1265  1265 E traceResume: 	at android.os.Looper.loopOnce(Looper.java:201)
01-16 06:26:45.387  1265  1265 E traceResume: 	at android.os.Looper.loop(Looper.java:288)
01-16 06:26:45.387  1265  1265 E traceResume: 	at android.app.ActivityThread.main(ActivityThread.java:7870)
01-16 06:26:45.387  1265  1265 E traceResume: 	at java.lang.reflect.Method.invoke(Native Method)
01-16 06:26:45.387  1265  1265 E traceResume: 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
01-16 06:26:45.387  1265  1265 E traceResume: 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)

onResume 的时候 执行 IApplicationThread.aidl 的 scheduleTransaction 堆栈

java 复制代码
01-16 07:37:38.101   576  1055 E traceReumeService: traceReumeServiceResumeActivityItem{procState=-1,updateProcState=false,isForward=true}
01-16 07:37:38.101   576  1055 E traceReumeService: java.lang.NullPointerException
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.server.wm.ActivityTaskSupervisor.realStartActivityLocked(ActivityTaskSupervisor.java:878)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.server.wm.RootWindowContainer.startActivityForAttachedApplicationIfNeeded(RootWindowContainer.java:2013)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.server.wm.RootWindowContainer.$r8$lambda$auelgeOhCvbItmS_07q5VFEb1ac(Unknown Source:0)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.server.wm.RootWindowContainer$$ExternalSyntheticLambda2.apply(Unknown Source:8)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.internal.util.function.pooled.PooledLambdaImpl.doInvoke(PooledLambdaImpl.java:318)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.internal.util.function.pooled.PooledLambdaImpl.invoke(PooledLambdaImpl.java:204)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.internal.util.function.pooled.OmniFunction.apply(OmniFunction.java:78)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.server.wm.ActivityRecord.forAllActivities(ActivityRecord.java:4260)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.server.wm.WindowContainer.forAllActivities(WindowContainer.java:1449)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.server.wm.WindowContainer.forAllActivities(WindowContainer.java:1442)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.server.wm.RootWindowContainer.lambda$attachApplication$15$RootWindowContainer(RootWindowContainer.java:1991)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.server.wm.RootWindowContainer$$ExternalSyntheticLambda20.accept(Unknown Source:6)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.server.wm.Task.forAllRootTasks(Task.java:3197)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.server.wm.WindowContainer.forAllRootTasks(WindowContainer.java:1825)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.server.wm.WindowContainer.forAllRootTasks(WindowContainer.java:1825)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.server.wm.WindowContainer.forAllRootTasks(WindowContainer.java:1825)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.server.wm.WindowContainer.forAllRootTasks(WindowContainer.java:1825)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.server.wm.WindowContainer.forAllRootTasks(WindowContainer.java:1825)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.server.wm.WindowContainer.forAllRootTasks(WindowContainer.java:1825)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.server.wm.WindowContainer.forAllRootTasks(WindowContainer.java:1818)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.server.wm.RootWindowContainer.attachApplication(RootWindowContainer.java:1977)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.server.wm.ActivityTaskManagerService$LocalService.attachApplication(ActivityTaskManagerService.java:6032)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.server.am.ActivityManagerService.attachApplicationLocked(ActivityManagerService.java:4591)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.server.am.ActivityManagerService.attachApplication(ActivityManagerService.java:4672)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at android.app.IActivityManager$Stub.onTransact(IActivityManager.java:2404)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:2518)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at android.os.Binder.execTransactInternal(Binder.java:1179)
01-16 07:37:38.101   576  1055 E traceReumeService: 	at android.os.Binder.execTransact(Binder.java:1143)
相关推荐
程思扬4 小时前
Android笔记: 实现点击事件透传到底部
android·前端·windows·经验分享·笔记·科技·ui
带电的小王5 小时前
Android Studio:Linux环境下安装与配置
android·linux·android studio
柯南二号7 小时前
Android 实现多语言功能
android·gitee
梦浪流云7 小时前
RK3576 Android14 状态栏和导航栏增加显示控制功能
android·java
我是大佬的大佬8 小时前
在Android Studio中如何实现contentprovider实验+SQLite数据库(保姆级教程)
android·开发语言·sqlite·android studio
Grassto9 小时前
Android adb 调试,不在手机上点击信任 “允许usb调试” 即可连接的方式(手机需root)
android·adb
大G哥10 小时前
Android 13 Hotseat定制化修改——001 hotseat布局方向
android
我命由我1234513 小时前
11-2.Android 项目结构 - themes.xml 文件基础解读
android·xml·java·java-ee·gitee·android jetpack·android runtime
还记得梦想吗14 小时前
android adb 无线连接 (wifi)
android·linux·adb