【Android】Android Framework系列--Launcher3各启动场景源码分析

Android Framework系列–Launcher3各启动场景源码分析

Launcher3启动场景

Launcher3是Android系统提供的默认桌面应用(Launcher),它的源码路径在“packages/apps/Launcher3/”。
Launcher3的启动场景主要包括:

  • 开机后启动:开机时,android ams服务拉起Launcher
  • 按键启动:比如短压home键,android wms中的PhoneWindowManager拉起Launcher
  • 异常崩溃后启动:Launcher异常崩溃后,android ams再次拉起Launcher

针对这三种情况,分析一下Aosp源码如何实现。
源码基于Android10版本,时序图基于Android12(基本上与Android10的流程差不多,可以参考)。
下述说明中Launcher3和Launcher意思相同。

开机启动Launcher

在这里插入图片描述

Launcher的开机启动由Android的AMS服务完成。
AMS在SystemReady阶段会调用startHomeOnAllDisplays函数。Android支持多Display(虚拟Display或者由硬件上报的实际Display),多Display情况下一般Launcher会针对不同Display做不同的效果。

// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {// 启动Home,也就是LaunchermAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
}

调用ActivityTaskManagerInternal类型的接口startHomeOnAllDisplays,这个接口在ActivityTaskManagerService.java文件中实现。

// frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
final class LocalService extends ActivityTaskManagerInternal {@Overridepublic boolean startHomeOnAllDisplays(int userId, String reason) {synchronized (mGlobalLock) {// 这个对象是RootActivityContainer类型return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);}}
}

接下来调用RootActivityContainer的接口startHomeOnAllDisplays,第二个参数reson的值为“systemReady”。

// frameworks/base/services/core/java/com/android/server/wm/RootActivityContainer.java
boolean startHomeOnAllDisplays(int userId, String reason) {boolean homeStarted = false;for (int i = mActivityDisplays.size() - 1; i >= 0; i--) {final int displayId = mActivityDisplays.get(i).mDisplayId;homeStarted |= startHomeOnDisplay(userId, reason, displayId);}return homeStarted;
}

遍历mActivityDisplays对于所有处于Active状态的Display调用startHomeOnDisplay,在每个Display上都启动Home(Launcher)。

// frameworks/base/services/core/java/com/android/server/wm/RootActivityContainer.java
boolean startHomeOnDisplay(int userId, String reason, int displayId) {// allowInstrumenting :false// fromHomeKey : falsereturn startHomeOnDisplay(userId, reason, displayId, false /* allowInstrumenting */,false /* fromHomeKey */);
}boolean startHomeOnDisplay(int userId, String reason, int displayId, boolean allowInstrumenting,boolean fromHomeKey) {// 如果DisplayID是非法的,使用当前处于顶层焦点的 Display// Fallback to top focused display if the displayId is invalid.if (displayId == INVALID_DISPLAY) {displayId = getTopDisplayFocusedStack().mDisplayId;}// 构建一个IntentIntent homeIntent = null;ActivityInfo aInfo = null;if (displayId == DEFAULT_DISPLAY) {// 如果DisplayID是默认的Display(一般是主屏)// 调用ActivityTaskManagerService的getHomeIntent,拿到用来启动Home的IntenthomeIntent = mService.getHomeIntent();// 查找当前系统里包含 android.intent.category.HOME的Activity。// 择优选择使用哪个ActivityaInfo = resolveHomeActivity(userId, homeIntent);} else if (shouldPlaceSecondaryHomeOnDisplay(displayId)) {// 如果不是默认Display屏幕Pair<ActivityInfo, Intent> info = resolveSecondaryHomeActivity(userId, displayId);aInfo = info.first;homeIntent = info.second;}if (aInfo == null || homeIntent == null) {return false;}// 判断是否运行启动Homeif (!canStartHomeOnDisplay(aInfo, displayId, allowInstrumenting)) {return false;}// 更新Home Intent// Updates the home component of the intent.homeIntent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));homeIntent.setFlags(homeIntent.getFlags() | FLAG_ACTIVITY_NEW_TASK);// 如果是从HomeKey启动的,添加额外参数// Updates the extra information of the intent.if (fromHomeKey) {homeIntent.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, true);}// Update the reason for ANR debugging to verify if the user activity is the one that// actually launched.final String myReason = reason + ":" + userId + ":" + UserHandle.getUserId(aInfo.applicationInfo.uid) + ":" + displayId;// 启动HomemService.getActivityStartController().startHomeActivity(homeIntent, aInfo, myReason,displayId);return true;
}

startHomeOnDisplay函数中查询当前系统中包含 android.intent.category.HOME信息的Activity(resolveHomeActivity),如果找到了多个Activity则选择高优先级的。根据查找的Activity信息构建Intent,使用ActivityTaskManagerService的ActivityStartController启动Home对应的Activity。
getHomeIntent函数在ActivityTaskManagerService中实现。

// frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
Intent getHomeIntent() {// String mTopAction = Intent.ACTION_MAIN;Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);intent.setComponent(mTopComponent);intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {// 非FactoryTest模式下走这里。// android.intent.category.HOMEintent.addCategory(Intent.CATEGORY_HOME);}return intent;
}

resolveHomeActivity函数用于查找包含android.intent.category.HOME信息的Activity。实现上是通过PMS完成的。

// frameworks/base/services/core/java/com/android/server/wm/RootActivityContainer.java
/*** This resolves the home activity info.* @return the home activity info if any.*/
@VisibleForTesting
ActivityInfo resolveHomeActivity(int userId, Intent homeIntent) {final ComponentName comp = homeIntent.getComponent();try {if (comp != null) {// Factory test.} else {final String resolvedType =homeIntent.resolveTypeIfNeeded(mService.mContext.getContentResolver());// 调用PMS查找信息final ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(homeIntent, resolvedType, flags, userId);if (info != null) {aInfo = info.activityInfo;}}} catch (RemoteException e) {// ignore}aInfo = new ActivityInfo(aInfo);aInfo.applicationInfo = mService.getAppInfoForUser(aInfo.applicationInfo, userId);return aInfo;
}

当找到所需信息后,调用ActivityStartController的startHomeActivity启动Home。该接口与AMS的startActivity和startActivityAsUser实现上基本原理一样,都是通过Intent启动Activity(fork一个进程出来)

// frameworks/base/services/core/java/com/android/server/wm/ActivityStartController.java
void startHomeActivity(Intent intent, ActivityInfo aInfo, String reason, int displayId) {final ActivityOptions options = ActivityOptions.makeBasic();options.setLaunchWindowingMode(WINDOWING_MODE_FULLSCREEN);if (!ActivityRecord.isResolverActivity(aInfo.name)) {// The resolver activity shouldn't be put in home stack because when the foreground is// standard type activity, the resolver activity should be put on the top of current// foreground instead of bring home stack to front.options.setLaunchActivityType(ACTIVITY_TYPE_HOME);}options.setLaunchDisplayId(displayId);// 启动ActivitymLastHomeActivityStartResult = obtainStarter(intent, "startHomeActivity: " + reason).setOutActivity(tmpOutRecord).setCallingUid(0).setActivityInfo(aInfo).setActivityOptions(options.toBundle()).execute();mLastHomeActivityStartRecord = tmpOutRecord[0];final ActivityDisplay display =mService.mRootActivityContainer.getActivityDisplay(displayId);final ActivityStack homeStack = display != null ? display.getHomeStack() : null;if (homeStack != null && homeStack.mInResumeTopActivity) {// If we are in resume section already, home activity will be initialized, but not// resumed (to avoid recursive resume) and will stay that way until something pokes it// again. We need to schedule another resume.mSupervisor.scheduleResumeTopActivities();}
}

短压Home键启动Launcher

在这里插入图片描述

短压与长按区分,点一下Home键就属于短压。短压Home键后,Android会启动Home。

// frameworks/base/services/core/java/com/android/server/input/InputManagerService.java// Native callback.
private long interceptKeyBeforeDispatching(IBinder focus, KeyEvent event, int policyFlags) {// native层的 inputservice,通过这个接口上报回调return mWindowManagerCallbacks.interceptKeyBeforeDispatching(focus, event, policyFlags);
}
// frameworks/base/services/core/java/com/android/server/wm/InputManagerCallback.java
/**
* Provides an opportunity for the window manager policy to process a key before
* ordinary dispatch.
*/
@Override
public long interceptKeyBeforeDispatching(IBinder focus, KeyEvent event, int policyFlags) {WindowState windowState = mService.windowForClientLocked(null, focus, false);return mService.mPolicy.interceptKeyBeforeDispatching(windowState, event, policyFlags);
}

mService是WindowManagerService类型,WindowManagerService中的mPolicy是PhoneWindowManager。PhoneWindowManager作为WMS的Policy配置文件,专门用来处理与UI行为有关的事件。PhoneWindowManager会拦截HomeKey事件进行相应处理后选择不再派发Home(PhoneWindowManager处理完就不需要其他人处理了),或者继续派发HomeKey给当前焦点View。

// frameworks/base/services/core/java/com/android/server/policy/PhoneWindowManager.java
private long interceptKeyBeforeDispatchingInner(WindowState win, KeyEvent event,int policyFlags) {final boolean keyguardOn = keyguardOn();final int keyCode = event.getKeyCode();final int repeatCount = event.getRepeatCount();final int metaState = event.getMetaState();final int flags = event.getFlags();final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;final boolean canceled = event.isCanceled();final int displayId = event.getDisplayId();// First we always handle the home key here, so applications// can never break it, although if keyguard is on, we do let// it handle it, because that gives us the correct 5 second// timeout.if (keyCode == KeyEvent.KEYCODE_HOME) {// 处理HomeKeyDisplayHomeButtonHandler handler = mDisplayHomeButtonHandlers.get(displayId);if (handler == null) {handler = new DisplayHomeButtonHandler(displayId);mDisplayHomeButtonHandlers.put(displayId, handler);}return handler.handleHomeButton(win, event);} else if (keyCode == KeyEvent.KEYCODE_MENU) {// 省略}
}/** A handler to handle home keys per display */
private class DisplayHomeButtonHandler {int handleHomeButton(WindowState win, KeyEvent event) {final boolean keyguardOn = keyguardOn();final int repeatCount = event.getRepeatCount();final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;final boolean canceled = event.isCanceled();// If we have released the home key, and didn't do anything else// while it was pressed, then it is time to go home!if (!down) {// 省略// Post to main thread to avoid blocking input pipeline.// 处理短压HomemHandler.post(() -> handleShortPressOnHome(mDisplayId));return -1;}// 省略return -1;}
}private void handleShortPressOnHome(int displayId) {// Turn on the connected TV and switch HDMI input if we're a HDMI playback device.final HdmiControl hdmiControl = getHdmiControl();if (hdmiControl != null) {hdmiControl.turnOnTv();}// If there's a dream running then use home to escape the dream// but don't actually go home.if (mDreamManagerInternal != null && mDreamManagerInternal.isDreaming()) {mDreamManagerInternal.stopDream(false /*immediate*/);return;}// 启动Home// Go home!launchHomeFromHotKey(displayId);
}

PhoneWindowManager针对每个Display创建一个DisplayHomeButtonHandler ,通过它处理HomeKey。在启动Home期间如果开始了dream模式(类似于屏保),会先退出dream。最后调用launchHomeFromHotKey来启动Home,后续流程基本上与Home开机启动一致了。

Launcher异常崩溃后的自启动

在这里插入图片描述
Launcher意外退出(比如崩溃了)时,会触发AMS的forceStopPackage。AMS会再次将Home拉起。

//frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
@Override
public void forceStopPackage(final String packageName, int userId) {try {IPackageManager pm = AppGlobals.getPackageManager();synchronized(this) {int[] users = userId == UserHandle.USER_ALL? mUserController.getUsers() : new int[] { userId };for (int user : users) {if (mUserController.isUserRunning(user, 0)) {// 对每个运行的User,停掉 packageName对应的应用forceStopPackageLocked(packageName, pkgUid, "from pid " + callingPid);finishForceStopPackageLocked(packageName, pkgUid);}}}} finally {Binder.restoreCallingIdentity(callingId);}
}

forceStopPackageLocked函数中,会先Kill掉应用对应的进程。然后 resume focused app,在resume的过程中会拉起Home。

//frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
@GuardedBy("this")
final boolean forceStopPackageLocked(String packageName, int appId,boolean callerWillRestart, boolean purgeCache, boolean doit,boolean evenPersistent, boolean uninstalling, int userId, String reason) {// kill进程boolean didSomething = mProcessList.killPackageProcessesLocked(packageName, appId, userId,ProcessList.INVALID_ADJ, callerWillRestart, true /* allowRestart */, doit,evenPersistent, true /* setRemoved */,packageName == null ? ("stop user " + userId) : ("stop " + packageName));if (doit) {if (purgeCache && packageName != null) {AttributeCache ac = AttributeCache.instance();if (ac != null) {ac.removePackage(packageName);}}if (mBooted) {// resume focused app// 通过这个函数重新拉起HomemAtmInternal.resumeTopActivities(true /* scheduleIdle */);}}return didSomething;
}

调用ActivityTaskManagerServiced的resumeTopActivities函数。在 Home崩溃的情况下,调用这个函数,可以保证Home重新被拉起(这个函数最终会调用到RootActivityContainer 的resumeHomeActivity函数。感兴趣的可以继续顺着代码往下看)

//frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
@Override
public void resumeTopActivities(boolean scheduleIdle) {synchronized (mGlobalLock) {mRootActivityContainer.resumeFocusedStacksTopActivities();if (scheduleIdle) {mStackSupervisor.scheduleIdleLocked();}}
}// frameworks/base/services/core/java/com/android/server/wm/RootActivityContainer.java
boolean resumeFocusedStacksTopActivities(ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {// 省略if (!resumedOnDisplay) {// In cases when there are no valid activities (e.g. device just booted or launcher// crashed) it's possible that nothing was resumed on a display. Requesting resume// of top activity in focused stack explicitly will make sure that at least home// activity is started and resumed, and no recursion occurs.final ActivityStack focusedStack = display.getFocusedStack();if (focusedStack != null) {focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions);}}}return result;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/204015.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【开源】基于JAVA的开放实验室管理系统

项目编号&#xff1a; S 013 &#xff0c;文末获取源码。 \color{red}{项目编号&#xff1a;S013&#xff0c;文末获取源码。} 项目编号&#xff1a;S013&#xff0c;文末获取源码。 目录 一、摘要1.1 项目介绍1.2 项目录屏 二、研究内容2.1 实验室类型模块2.2 实验室模块2.3 实…

Java网络爬虫实战

List item 文章目录 ⭐️写在前面的话⭐️&#x1f4cc;What is it?分类网络爬虫按照系统结构和实现技术&#xff0c;大致可以分为以下几种类型&#xff1a;通用网络爬虫&#xff08;General Purpose Web Crawler&#xff09;、聚焦网络爬虫&#xff08;Focused Web Crawler&a…

计算机丢失vcomp140.dll是什么意思,如何解决与修复(附教程)

vcomp140.dll缺失的5种解决方法以及vcomp140.dll缺失原因 引言&#xff1a; 在日常使用电脑的过程中&#xff0c;我们可能会遇到一些错误提示&#xff0c;其中之一就是“vcomp140.dll缺失”。这个错误提示通常出现在运行某些程序或游戏时&#xff0c;给使用者带来了困扰。本文…

github访问失败

1. 问题场景 今天了解到notepad可以安装许多插件&#xff0c;但是自动下载插件时总是失败&#xff0c;这些插件的下载源都是github&#xff0c;将地址复制到浏览器也打不开&#xff0c;所以查了下github的访问问题&#xff0c;目前插件已正常下载。 2. 解决方法 gitee上搜索…

大数据数据仓库,Sqoop--学习笔记

数据仓库介绍 1. 数据仓库概念 数据仓库概念创始人在《建立数据仓库》一书中对数据仓库的定义是&#xff1a;数据仓库&#xff08;Data Warehouse&#xff09;是一个面向主题的&#xff08;Subject Oriented&#xff09;、数据集成的&#xff08;Integrated&#xff09;、相对…

【MATLAB源码-第86期】基于matlab的QC-LDPC码性能仿真,输出误码率曲线。

操作环境&#xff1a; MATLAB 2022a 1、算法描述 QC-LDPC&#xff08;准循环低密度奇偶校验&#xff09;编码是一种高效的错误校正编码方式&#xff0c;广泛应用于通信系统和数据存储中以提高数据的可靠性。它是低密度奇偶校验&#xff08;LDPC&#xff09;编码的一种特殊形…

Zookeeper分布式锁实现Curator十一问

前面我们通过Redis分布式锁实现Redisson 15问文章剖析了Redisson的源码&#xff0c;理清了Redisson是如何实现的分布式锁和一些其它的特性。这篇文章就来接着剖析Zookeeper分布式锁的实现框架Curator的源码&#xff0c;看看Curator是如何实现Zookeeper分布式锁的&#xff0c;以…

wpf使用CefSharp.OffScreen模拟网页登录,并获取身份cookie,C#后台执行js

目录 框架信息&#xff1a;MainWindow.xamlMainWindow.xaml.cs爬取逻辑模拟登录拦截请求Cookie获取 CookieVisitorHandle完整代码参考项目 框架信息&#xff1a; CefSharp.OffScreen.NETCore 109.1.110 .NET 7 CefSharp.OffScreen.NETCore v114.2.100 第一版使用这个&#x…

shiro整合redis

shiro整合redis 前言&#xff1a;shiro默认的session是存储在jvm内存中的&#xff0c;这样会导致java服务内存占用更大以及一旦服务器宕机或者版本迭代需要重启服务时&#xff0c;缓存中的数据不能恢复&#xff0c;导致用户需要重新登录认证&#xff0c;体验很差。因此利用第三…

C++ 泛型编程,函数模版和类模版

1.泛型编程 泛型编程&#xff1a;编写与类型无关的通用代码&#xff0c;是代码复用的一种手段。模板是泛型编程的基础 就比如说活字印刷术&#xff0c;就是提供一个模具&#xff0c;然后根据模具来印刷出不同的字。 泛型编程跟着类似&#xff0c;提供一个模版&#xff0c;根据这…

哈希表——闭散列表

该哈希表实现是闭散列实现法。 闭散列表&#xff1a; 闭散列&#xff1a;也叫开放定址法&#xff0c;当发生哈希冲突时&#xff0c;如果哈希表未被装满&#xff0c;说明在哈希表中必然还有空位置&#xff0c;那么可以把key存放到冲突位置中的“下一个” 空位置中去。 那如何寻…

96.STL-遍历算法 transform

目录 transform 语法&#xff1a; 功能描述&#xff1a; 函数原型&#xff1a; 代码示例&#xff1a; transform 是 C 标准模板库&#xff08;STL&#xff09;中的一个算法&#xff0c;用于对一个范围内的元素进行转换并将结果存储到另一个范围。以下是简要解释和一个示例…

【开源】基于JAVA的衣物搭配系统

项目编号&#xff1a; S 016 &#xff0c;文末获取源码。 \color{red}{项目编号&#xff1a;S016&#xff0c;文末获取源码。} 项目编号&#xff1a;S016&#xff0c;文末获取源码。 目录 一、摘要1.1 项目介绍1.2 项目录屏 二、研究内容2.1 衣物档案模块2.2 衣物搭配模块2.3 衣…

成为AI产品经理——TPR、FPR、ROC、AUC

目录 一、PR图、BEP 1.PR图 2.BEP 二、灵敏度、特异度 1.灵敏度 2.特异度 三、真正率、假正率 1.真正率 2.假正率 三、ROC、AUC 1.ROC 2.AUC 四、KS值 一、PR图、BEP 1.PR图 二分类问题模型通常输出的是一个概率值&#xff0c;我们需要设定一个阈值&#xff…

手机爬虫用Fiddler详细教程

如果你正在进行手机爬虫的工作&#xff0c;那么一款强大而又实用的网络调试工具Fiddler将会是你的好帮手。今天&#xff0c;我将和大家分享一份详细的Fiddler教程&#xff0c;教你如何使用它来轻松捕获和分析手机App的网络请求。让我们一起来探索Fiddler的功能和操作&#xff0…

IntelliJ IDEA 16创建Web项目

首先要理解一个概念&#xff1a;在IntelliJ IDEA中“new Project”相当于eclipse中的工作空间&#xff08;Workspace&#xff09;&#xff0c;而“new Module”相当于eclipse中的工程&#xff08;Project&#xff09;。以下均采用Intellij的说法&#xff0c;请自行对照转换理解…

opencv-图像平滑

高斯平滑 高斯平滑即采用高斯卷积核对图像矩阵进行卷积操作。高斯卷积核是一个近似服从高斯分布的矩阵&#xff0c;随着距离中心点的距离增加&#xff0c;其值变小。这样进行平滑处理时&#xff0c;图像矩阵中锚点处像素值权重大&#xff0c;边缘处像素值权重小。 import cv2 …

PTA-6-48 使用面向对象的思想编写程序描述动物

题目&#xff1a; 使用面向对象的思想编写程序描述动物&#xff0c;说明&#xff1a; &#xff08;1) 分析兔子和青蛙的共性&#xff0c;定义抽象的动物类&#xff0c;拥有一些动物共有的属性&#xff1a;名字、颜色、类别&#xff08;哺乳类、非哺乳类&#xff09;&#xff0c…

在Windows WSL (Linux的Windows子系统)上运行的Ubuntu如何更改主机名

在Windows 安装的Ubuntu&#xff0c;如何修改主机名。有列了两种方法&#xff0c;提供给大家参照。 文章目录 方法一&#xff1a;hostname指令修改方法二&#xff1a;修改配置文件修改hostnanmewsl.conf 文件配置选项推荐阅读 方法一&#xff1a;hostname指令修改 hostname指…