AMS:startActivity桌面启动应用

startActivity桌面启动应用

android12-release


1. Launcher点击应用图标

packages/apps/Launcher3/src/com/android/launcher3/touch/ItemClickHandler.java
packages/apps/Launcher3/src/com/android/launcher3/Launcher.java
packages/apps/Launcher3/src/com/android/launcher3/BaseDraggingActivity.java
packages/apps/Launcher3/src/com/android/launcher3/BaseActivity.java

onClickAppShortcut -> startAppShortcutOrInfoActivity -> launcher.startActivitySafely -> startActivity()最后调用到Activity.java中。

其中intent包含信息:
action = “android.intent.action.MAIN”
category=“android.intent.category.LAUNCHER”
cmp=“[包名]/.MainActivity”

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 配合android:taskAffinity,默认为包名,冷启动应用时Activity在新的任务栈中启动

<activity android:name=".MainActivity"  
      android:label="@string/app_name">  
       <intent-filter>  
        <action android:name="android.intent.action.MAIN" />  
        <category android:name="android.intent.category.LAUNCHER" />  
    </intent-filter>  
</activity>  

2. 桌面Activity – Instrumentation – AMS/ATMS

  • mParent 应用首次启动所以mParent为空。
  • mMainThread.getApplicationThread() 获取ApplicationThread成员变量,是一个Binder对象
  • mToken Activity类的成员变量,它是一个Binder对象的远程接口
  • ActivityTaskManager.getService() 获取Context.ACTIVITY_TASK_SERVICE 即是 ActivityTaskManagerService
  • Instrumentation.java 用来监控应用程序和系统的交互
  • checkStartActivityResult(result, intent); 检查是否启动成功

startActivity() -> startActivityForResult -> mInstrumentation.execStartActivity -> ActivityTaskManager.getService().startActivity

frameworks/base/core/java/android/app/Activity.java
frameworks/base/core/java/android/app/Instrumentation.java

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
        if (mParent == null) {
            options = transferSpringboardActivityOptions(options);
            Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);
            // ... ...
        } else {
            // ... ...
        }
    }
    public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
        // ... ...
        try {
            intent.migrateExtraStreamToClipData(who);
            intent.prepareToLeaveProcess(who);
            int result = ActivityTaskManager.getService().startActivity(whoThread,
                    who.getOpPackageName(), who.getAttributionTag(), intent,
                    intent.resolveTypeIfNeeded(who.getContentResolver()), token,
                    target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
    }

2.1 ActivityTaskManager.getService()

在这里插入图片描述

3. Binder IPC调用到 ActivityTaskManagerService

frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
frameworks/base/services/core/java/com/android/server/wm/ActivityStartController.java
frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java

ActivityTaskManager.getService().startActivity -> startActivityAsUser() -> getActivityStartController().obtainStarter ........ execute() -> executeRequest(mRequest) -> startActivityUnchecked() -> startActivityInner()
在这里插入图片描述
在这里插入图片描述

  • obtainStarter(intent, "startActivityAsUser")工厂模式mFactory.obtain().setIntent(intent).setReason(reason)获取ActivityStarter
  • executeRequest(mRequest)这里输出START u日志,一般定制都会加上pid打印
    在这里插入图片描述
  • ActivityRecord r,sourceRecord信息
  • startActivityInner()该方法有许多参数处理,如setInitialState\computeLaunchingTaskFlags\computeSourceStack\mIntent.setFlags(mLaunchFlags)\computeLaunchParams
  • startActivityInner() 这里wm_create_taskwm_create_activity
    在这里插入图片描述
if (newTask) {
     EventLogTags.writeWmCreateTask(mStartActivity.mUserId,
             mStartActivity.getTask().mTaskId);
 }
 mStartActivity.logStartActivity(
         EventLogTags.WM_CREATE_ACTIVITY, mStartActivity.getTask());
  • mDoResume移到栈顶显示resumeFocusedTasksTopActivities
    在这里插入图片描述

3.1 先startPausingLocked

mRootWindowContainer.resumeFocusedTasksTopActivities -> resumeTopActivityUncheckedLocked -> resumeTopActivityInnerLocked -> 先startPausingLocked后mTaskSupervisor.startSpecificActivity(next, true, true)

next.attachedToProcess()此时由于第一次(冷启动)为false,主要在Task.java操作resumeTopActivityInnerLocked()
在这里插入图片描述 在这里插入图片描述

  • 此时当前mResumedActivity != null,即为桌面Launcher,先startPausingLocked() 执行Pausing过程,并输出日志wm_pause_activity
if (mResumedActivity != null) {
    ProtoLog.d(WM_DEBUG_STATES, "resumeTopActivityLocked: Pausing %s", mResumedActivity);
    pausing |= startPausingLocked(false /* uiSleeping */, next,
            "resumeTopActivityInnerLocked");
}
  • prev = mResumedActivity、mPausingActivity = prev赋值mPausingActivity,并设置状态prev.setState(PAUSING, "startPausingLocked")

  • EventLogTags.writeWmPauseActivity() Event日志

  • mAtmService.getLifecycleManager().scheduleTransaction()执行PauseActivityItem,通过ActivityThread、Instrumentation.callActivityOnPause()通知到Activity onPause(),并输出wm_on_paused_calledAndroid P Basic lifecycle transaction containers --设计模式体现之策略模式
    在这里插入图片描述

  • completePauseLocked(false, resuming) pause完成,并设置状态prev.setState(PAUSED, "completePausedLocked");

frameworks/base/services/core/java/com/android/server/wm/Task.java

final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
         ActivityRecord resuming, String reason) {
     // ... ...
     ActivityRecord prev = mResumedActivity;
     // ... ...
     ProtoLog.v(WM_DEBUG_STATES, "Moving to PAUSING: %s", prev);
     mPausingActivity = prev;
     mLastPausedActivity = prev;
     if (prev.isNoHistory() && !mTaskSupervisor.mNoHistoryActivities.contains(prev)) {
         mTaskSupervisor.mNoHistoryActivities.add(prev);
     }
     prev.setState(PAUSING, "startPausingLocked");
     prev.getTask().touchActiveTime();
     // ... ...
     boolean didAutoPip = false;
     if (prev.attachedToProcess()) {
         if (shouldAutoPip) {
             // ... ...
         } else {
             ProtoLog.v(WM_DEBUG_STATES, "Enqueueing pending pause: %s", prev);
             try {
                 EventLogTags.writeWmPauseActivity(prev.mUserId, System.identityHashCode(prev),
                         prev.shortComponentName, "userLeaving=" + userLeaving, reason);

                 mAtmService.getLifecycleManager().scheduleTransaction(prev.app.getThread(),
                         prev.appToken, PauseActivityItem.obtain(prev.finishing, userLeaving,
                                 prev.configChangeFlags, pauseImmediately));
             } catch (Exception e) {
                 // ... ...
             }
         }
     } else {
         // ... ...
     }
     // ... ...
         // ... ...
         if (pauseImmediately) {
             // If the caller said they don't want to wait for the pause, then complete
             // the pause now.
             completePauseLocked(false, resuming);
             return false;

         }
     // ... ...
 }
  • 先走这里mTaskSupervisor.startSpecificActivity,执行realStartActivityLocked();没有启动执行mService.startProcessAsync()

3.2 startSpecificActivity启动:AMS/ATMS -- Instrumentation -- 应用Activity

  • WindowProcessController wpc第一次启动获取到的是null;mService.startProcessAsync()先fork应用进程

frameworks/base/services/core/java/com/android/server/wm/ActivityTaskSupervisor.java

void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
    // Is this activity's application already running?
    final WindowProcessController wpc =
            mService.getProcessController(r.processName, r.info.applicationInfo.uid);

    boolean knownToBeDead = false;
    if (wpc != null && wpc.hasThread()) {
        try {
            realStartActivityLocked(r, wpc, 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.
        knownToBeDead = true;
    }

    r.notifyUnknownVisibilityLaunchedForKeyguardTransition();

    final boolean isTop = andResume && r.isTopRunningActivity();
    mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
}
3.2.1 启动ActivityThread(内部成员ApplicationThread)
  • startProcessAsync通过ATMS/AMS走到ProcessList.javastartProcess()调用Process.start,通过ZYGOTE_PROCESS.start fork生成进程,最后执行到 ActivityThread.main() 方法回调AMS.attachApplication
    public static void main(String[] args) {
        // ... ...
        Looper.prepareMainLooper();
        // ... ...
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);
        // ... ...
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

相关查看ActivityThread应用进程

  • ProcessList.java中handleProcessStartedLocked输出am_proc_startAMS.attachApplication输出am_proc_bound
EventLog.writeEvent(EventLogTags.AM_PROC_START,
        UserHandle.getUserId(app.getStartUid()), pid, app.getStartUid(),
        app.processName, app.getHostingRecord().getType(),
        app.getHostingRecord().getName() != null ? app.getHostingRecord().getName() : "");
        
EventLogTags.writeAmProcBound(app.userId, pid, app.processName);
  • 几经attachApplication:AMS.attachApplication -> ATMS.attachApplication -> RootWindowContainer.attachApplication(wpc) -> mTaskSupervisor.realStartActivityLocked();最终还是调用到realStartActivityLocked
  • AMS.attachApplicationthread.bindApplication()创建Instrumentationapp = data.info.makeApplication(data.restrictedBackupMode, null),并通过Instrumentation通知到Application:
mInstrumentation.onCreate(data.instrumentationArgs);
mInstrumentation.callApplicationOnCreate(app);
3.2.2 realStartActivityLocked()真正启动APP

ActivityThread.main() -> AMS.attachApplication -> ATMS.attachApplication -> RootWindowContainer.attachApplication(wpc) / startActivityForAttachedApplicationIfNeeded -> mTaskSupervisor.realStartActivityLocked()

  • Event日志wm_restart_activity
EventLogTags.writeWmRestartActivity(r.mUserId, System.identityHashCode(r),
          task.mTaskId, r.shortComponentName);
  • mService.getLifecycleManager().scheduleTransaction(clientTransaction);通知到Activity Resumed: wm_on_resume_called
mInstrumentation.callActivityOnResume(this);
EventLogTags.writeWmOnResumeCalled(mIdent, getComponentName().getClassName(), reason);
  • 与上面pause不同的是添加了LaunchActivityItem

frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
(Android P Basic lifecycle transaction containers--设计模式体现之策略模式)
在这里插入图片描述

  • TransactionExecutor先执行executeCallbacks即执行LaunchActivityItem,所以在Resuemed之前处理handleLaunchActivity()
  1. 初始化activity = mInstrumentation.newActivity()
  2. activity.attach() 处理WMS相关信息
  3. mInstrumentation.callActivityOnCreate()通知onCreate,设置ActivityClientRecord r.setState(ON_CREATE);
  4. executeLifecycleState(transaction)ON_CREATEON_RESUME之间添加ON_START流程: mHelper.getLifecyclePath(start, finish, excludeLastState)

frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java

    public void execute(ClientTransaction transaction) {
        // ... ...
        if (DEBUG_RESOLVER) Slog.d(TAG, transactionToString(transaction, mTransactionHandler));

        executeCallbacks(transaction);

        executeLifecycleState(transaction);
        mPendingActions.clear();
        if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
    }

frameworks/base/core/java/android/app/ActivityThread.java

    public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
        // ... ...
        // Make sure we are running with the most recent config.
        mConfigurationController.handleConfigurationChanged(null, null);

        if (localLOGV) Slog.v(
            TAG, "Handling launch of " + r);

        // Initialize before creating the activity
        if (ThreadedRenderer.sRendererEnabled
                && (r.activityInfo.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
            HardwareRenderer.preload();
        }
        WindowManagerGlobal.initialize();

        // Hint the GraphicsEnvironment that an activity is launching on the process.
        GraphicsEnvironment.hintActivityLaunch();

        final Activity a = performLaunchActivity(r, customIntent);
        // ... ...
    }

4. 时序图

在这里插入图片描述

在这里插入图片描述

待续~~~ 道阻且长


Log关键字:
ActivityTaskManager: START u|ActivityTaskManager: Displayed
wm_create_activity|wm_set_resumed_activity|wm_resume_activity|wm_on_resume_called|wm_activity_launch_time


06-13 23:14:02.056 1000 1787 10268 I wm_create_task: [0,109]
06-13 23:14:02.056 1000 1787 10268 I wm_create_activity: [0,103558740,109,com.tencent.mobileqq/.activity.SplashActivity,android.intent.action.MAIN,NULL,NULL,270532608]
06-13 23:14:02.059 1000 1787 10268 I wm_pause_activity: [0,3858326,com.miui.home/.launcher.Launcher,userLeaving=true]
06-13 23:14:02.067 10083 22061 22061 I wm_on_paused_called: [0,com.miui.home.launcher.Launcher,performPause,1]

06-13 23:14:02.114 1000 1787 3359 I wm_restart_activity: [0,103558740,109,com.tencent.mobileqq/.activity.SplashActivity]
06-13 23:14:02.117 1000 1787 3359 I wm_set_resumed_activity: [0,com.tencent.mobileqq/.activity.SplashActivity,minimalResumeActivityLocked]
06-13 23:14:02.876 10264 26092 26092 I wm_on_create_called: [0,com.tencent.mobileqq.activity.SplashActivity,performCreate,105]
06-13 23:14:02.878 10264 26092 26092 I wm_on_start_called: [0,com.tencent.mobileqq.activity.SplashActivity,handleStartActivity,1]
06-13 23:14:02.885 10264 26092 26092 I wm_on_resume_called: [0,com.tencent.mobileqq.activity.SplashActivity,RESUME_ACTIVITY,7]
06-13 23:14:02.899 10264 26092 26092 I wm_on_top_resumed_gained_called: [103558740,com.tencent.mobileqq.activity.SplashActivity,topStateChangedWhenResumed]
06-13 23:14:02.988 1000 1787 1839 I wm_activity_launch_time: [0,103558740,com.tencent.mobileqq/.activity.SplashActivity,954]


相关文章:

Android应用程序启动过程源代码分析
Android应用程序内部启动Activity过程(startActivity)的源代码分析
startActivity启动过程分析
【 Android 10 四大组件 】系列 – Activity 的“启动流程”
Android之Activity启动流程详解(基于api28)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xhBruce

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值