当前位置:   article > 正文

高通Android 8.1/9/10/11/12/13 通过包名设置默认launcher_android8.1怎么修改默认的launcher

android8.1怎么修改默认的launcher

背景:最近在封装供第三应用系统SDK 接口,遇到一个无法通过包名设置主launcher代码坑所以记录下。
 

  1. 涉及类roles.xml # <!---
  2.       ~ @see com.android.settings.applications.defaultapps.DefaultHomePreferenceController
  3.       ~ @see com.android.settings.applications.defaultapps.DefaultHomePicker
  4.       ~ @see com.android.server.pm.PackageManagerService#setHomeActivity(ComponentName, int)
  5.       -->
  6. DeaultAppActivity.java#onCreate
  7. DefaultAppChildFragment.java # onRoleChanged # addPreference
  8. AutoDefaultAppListFragment#onActivityCreated
  9. ManageRoleHolderStateLiveData.java #setRoleHolderAsUser
  10. HandheldDefaultAppFragment.java(packages/modules/Permission/PermissionController/src/com/android/permissioncontroller/role/ui/handheld)#newInstance
  11. RoleManager.java #addRoleHolderAsUser
  12. IRoleManager.aidl #addRoleHolderAsUser
  13. Role.java  #getDefaultHolders 
  14. TwoTargetPreference.java #OnSecondTargetClickListener
  15. PackageManagerShellCommand.java#runSetHomeActivity
  16. ResolverActivity.java # onCreate
  17. ParseActivityUtils #
  18. private static ParseResult<ParsedActivity> parseActivityOrAlias(ParsedActivity activity,
  19. ParsingPackage pkg, String tag, XmlResourceParser parser, Resources resources,
  20. TypedArray array, boolean isReceiver, boolean isAlias, boolean visibleToEphemeral,
  21. ParseInput input, int parentActivityNameAttr, int permissionAttr,
  22. int exportedAttr)

1、Android10 一开始我是这样写的,代码如下图所示。

  1. private void setDefaultLauncher3(Context context,String packageName,String className) {
  2. try {
  3. PackageManager pm = getPackageManager();
  4. Log.i("deflauncher", "deflauncher : PackageName = " + packageName + " ClassName = " + className);
  5. IntentFilter filter = new IntentFilter();
  6. filter.addAction("android.intent.action.MAIN");
  7. filter.addCategory("android.intent.category.HOME");
  8. filter.addCategory("android.intent.category.DEFAULT");
  9. Intent intent = new Intent(Intent.ACTION_MAIN);
  10. intent.addCategory(Intent.CATEGORY_HOME);
  11. List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
  12. final int N = list.size();
  13. ComponentName[] set = new ComponentName[N];
  14. int bestMatch = 0;
  15. for (int i = 0; i < N; i++) {
  16. ResolveInfo r = list.get(i);
  17. set[i] = new ComponentName(r.activityInfo.packageName,
  18. r.activityInfo.name);
  19. if (r.match > bestMatch) bestMatch = r.match;
  20. }
  21. ComponentName preActivity = new ComponentName(packageName, className);
  22. pm.addPreferredActivity(filter, bestMatch, set, preActivity);
  23. } catch (Exception e) {
  24. e.printStackTrace();
  25. }
  26. }

2、Android 10 具体添加位置参考在frameworks/base/core/java/android/content/pm/parsing/component/ParsedActivityUtils.java

3、写死launcher包名主activity类名方法如下代码所示 app.olauncher.MainActivity

  1. /**
  2. * This method shares parsing logic between Activity/Receiver/alias instances, but requires
  3. * passing in booleans for isReceiver/isAlias, since there's no indicator in the other
  4. * parameters.
  5. *
  6. * They're used to filter the parsed tags and their behavior. This makes the method rather
  7. * messy, but it's more maintainable than writing 3 separate methods for essentially the same
  8. * type of logic.
  9. */
  10. @NonNull
  11. private static ParseResult<ParsedActivity> parseActivityOrAlias(ParsedActivity activity,
  12. ParsingPackage pkg, String tag, XmlResourceParser parser, Resources resources,
  13. TypedArray array, boolean isReceiver, boolean isAlias, boolean visibleToEphemeral,
  14. ParseInput input, int parentActivityNameAttr, int permissionAttr,
  15. int exportedAttr) throws IOException, XmlPullParserException {
  16. String parentActivityName = array.getNonConfigurationString(parentActivityNameAttr, Configuration.NATIVE_CONFIG_VERSION);
  17. if (parentActivityName != null) {
  18. String packageName = pkg.getPackageName();
  19. String parentClassName = ParsingUtils.buildClassName(packageName, parentActivityName);
  20. if (parentClassName == null) {
  21. Log.e(TAG, "Activity " + activity.getName()
  22. + " specified invalid parentActivityName " + parentActivityName);
  23. } else {
  24. activity.setParentActivity(parentClassName);
  25. }
  26. }
  27. String permission = array.getNonConfigurationString(permissionAttr, 0);
  28. if (isAlias) {
  29. // An alias will override permissions to allow referencing an Activity through its alias
  30. // without needing the original permission. If an alias needs the same permission,
  31. // it must be re-declared.
  32. activity.setPermission(permission);
  33. } else {
  34. activity.setPermission(permission != null ? permission : pkg.getPermission());
  35. }
  36. final boolean setExported = array.hasValue(exportedAttr);
  37. if (setExported) {
  38. activity.exported = array.getBoolean(exportedAttr, false);
  39. }
  40. final int depth = parser.getDepth();
  41. int type;
  42. while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
  43. && (type != XmlPullParser.END_TAG
  44. || parser.getDepth() > depth)) {
  45. if (type != XmlPullParser.START_TAG) {
  46. continue;
  47. }
  48. final ParseResult result;
  49. if (parser.getName().equals("intent-filter")) {
  50. ParseResult<ParsedIntentInfo> intentResult = parseIntentFilter(pkg, activity,
  51. !isReceiver, visibleToEphemeral, resources, parser, input);
  52. if (intentResult.isSuccess()) {
  53. ParsedIntentInfo intent = intentResult.getResult();
  54. if (intent != null) {
  55. Log.e(TAG,"ZM activityName="+activity.getName());
  56. if("app.olauncher.MainActivity".equals(activity.getName()))
  57. {
  58. intent.addCategory("android.intent.category.HOME");
  59. intent.addCategory("android.intent.category.DEFAULT");
  60. intent.setPriority(1000);
  61. }
  62. activity.order = Math.max(intent.getOrder(), activity.order);
  63. activity.addIntent(intent);
  64. if (LOG_UNSAFE_BROADCASTS && isReceiver
  65. && pkg.getTargetSdkVersion() >= Build.VERSION_CODES.O) {
  66. int actionCount = intent.countActions();
  67. for (int i = 0; i < actionCount; i++) {
  68. final String action = intent.getAction(i);
  69. if (action == null || !action.startsWith("android.")) {
  70. continue;
  71. }
  72. if (!SAFE_BROADCASTS.contains(action)) {
  73. Slog.w(TAG,
  74. "Broadcast " + action + " may never be delivered to "
  75. + pkg.getPackageName() + " as requested at: "
  76. + parser.getPositionDescription());
  77. }
  78. }
  79. }
  80. }
  81. }
  82. result = intentResult;
  83. } else if (parser.getName().equals("meta-data")) {
  84. result = ParsedComponentUtils.addMetaData(activity, pkg, resources, parser, input);
  85. } else if (parser.getName().equals("property")) {
  86. result = ParsedComponentUtils.addProperty(activity, pkg, resources, parser, input);
  87. } else if (!isReceiver && !isAlias && parser.getName().equals("preferred")) {
  88. ParseResult<ParsedIntentInfo> intentResult = parseIntentFilter(pkg, activity,
  89. true /*allowImplicitEphemeralVisibility*/, visibleToEphemeral,
  90. resources, parser, input);
  91. if (intentResult.isSuccess()) {
  92. ParsedIntentInfo intent = intentResult.getResult();
  93. if (intent != null) {
  94. pkg.addPreferredActivityFilter(activity.getClassName(), intent);
  95. }
  96. }
  97. result = intentResult;
  98. } else if (!isReceiver && !isAlias && parser.getName().equals("layout")) {
  99. ParseResult<ActivityInfo.WindowLayout> layoutResult =
  100. parseActivityWindowLayout(resources, parser, input);
  101. if (layoutResult.isSuccess()) {
  102. activity.windowLayout = layoutResult.getResult();
  103. }
  104. result = layoutResult;
  105. } else {
  106. result = ParsingUtils.unknownTag(tag, pkg, parser, input);
  107. }
  108. if (result.isError()) {
  109. return input.error(result);
  110. }
  111. }
  112. if (!isAlias && activity.launchMode != LAUNCH_SINGLE_INSTANCE_PER_TASK
  113. && activity.metaData != null && activity.metaData.containsKey(
  114. ParsingPackageUtils.METADATA_ACTIVITY_LAUNCH_MODE)) {
  115. final String launchMode = activity.metaData.getString(
  116. ParsingPackageUtils.METADATA_ACTIVITY_LAUNCH_MODE);
  117. if (launchMode != null && launchMode.equals("singleInstancePerTask")) {
  118. activity.launchMode = LAUNCH_SINGLE_INSTANCE_PER_TASK;
  119. }
  120. }
  121. ParseResult<ActivityInfo.WindowLayout> layoutResult =
  122. resolveActivityWindowLayout(activity, input);
  123. if (layoutResult.isError()) {
  124. return input.error(layoutResult);
  125. }
  126. activity.windowLayout = layoutResult.getResult();
  127. if (!setExported) {
  128. boolean hasIntentFilters = activity.getIntents().size() > 0;
  129. if (hasIntentFilters) {
  130. final ParseResult exportedCheckResult = input.deferError(
  131. activity.getName() + ": Targeting S+ (version " + Build.VERSION_CODES.S
  132. + " and above) requires that an explicit value for android:exported be"
  133. + " defined when intent filters are present",
  134. DeferredError.MISSING_EXPORTED_FLAG);
  135. if (exportedCheckResult.isError()) {
  136. return input.error(exportedCheckResult);
  137. }
  138. }
  139. activity.exported = hasIntentFilters;
  140. }
  141. return input.success(activity);
  142. }

4、Android 10 在ResolverActivity.java 中onCreate方法中 执行以下代码,代码路径 /frameworks/base/core/java/com/android/internal/app/ResolverActivity.java

  1. protected void onCreate(Bundle savedInstanceState, Intent intent,
  2. CharSequence title, int defaultTitleRes, Intent[] initialIntents,
  3. List<ResolveInfo> rList, boolean supportsAlwaysUseOption) {
  4. setTheme(appliedThemeResId());
  5. super.onCreate(savedInstanceState);
  6. if (mResolvingHome) {
  7. setDefaultLauncher3();
  8. finish();
  9. return;
  10. }

5、灵活一点如果动态设置launcher流程又不一样,下图是Setttings默认主屏幕应用  launcher列表选项(这个界面radiobutton控件通过preference动态添加 这个addPreference(preference):

6、Android 12 点击事件位置代码路径packages/modules/Permission/PermissionController/src/com/android/permissioncontroller/role/ui/DefaultAppChildFragment.java

  1. private void addPreference(@NonNull String key, @NonNull Drawable icon,
  2. @NonNull CharSequence title, boolean checked, @Nullable ApplicationInfo applicationInfo,
  3. @NonNull ArrayMap<String, Preference> oldPreferences,
  4. @NonNull PreferenceScreen preferenceScreen, @NonNull Context context) {
  5. TwoStatePreference preference = (TwoStatePreference) oldPreferences.get(key);
  6. if (preference == null) {
  7. preference = requirePreferenceFragment().createApplicationPreference(context);
  8. preference.setKey(key);
  9. preference.setIcon(icon);
  10. preference.setTitle(title);
  11. preference.setPersistent(false);
  12. preference.setOnPreferenceChangeListener((preference2, newValue) -> false);
  13. preference.setOnPreferenceClickListener(this);
  14. }
  15. Log.e("DefaultAppChildFragment","addPreference");
  16. preference.setChecked(checked);
  17. if (applicationInfo != null) {
  18. mRole.prepareApplicationPreferenceAsUser(preference, applicationInfo, mUser, context);
  19. }
  20. preferenceScreen.addPreference(preference);
  21. }

logcat日志

 DefaultAppChildFragment com.android.permissioncontroller     E  addPreference

7、另外一种通过指令去设置 adb shell pm set-home-activity  app.olauncher.debug (主launcher包名),验证过是没问题的。

8、实际调用还是通过RoleManager#addRoleHolderAsUser方法去添加为主Launcher

代码路径packages\modules\Permission\framework-s\java\android\app\role\RoleManager.java

  1. /**
  2. * Add a specific application to the holders of a role. If the role is exclusive, the previous
  3. * holder will be replaced.
  4. * <p>
  5. * <strong>Note:</strong> Using this API requires holding
  6. * {@code android.permission.MANAGE_ROLE_HOLDERS} and if the user id is not the current user
  7. * {@code android.permission.INTERACT_ACROSS_USERS_FULL}.
  8. *
  9. * @param roleName the name of the role to add the role holder for
  10. * @param packageName the package name of the application to add to the role holders
  11. * @param flags optional behavior flags
  12. * @param user the user to add the role holder for
  13. * @param executor the {@code Executor} to run the callback on.
  14. * @param callback the callback for whether this call is successful
  15. *
  16. * @see #getRoleHoldersAsUser(String, UserHandle)
  17. * @see #removeRoleHolderAsUser(String, String, int, UserHandle, Executor, Consumer)
  18. * @see #clearRoleHoldersAsUser(String, int, UserHandle, Executor, Consumer)
  19. *
  20. * @hide
  21. */
  22. @RequiresPermission(Manifest.permission.MANAGE_ROLE_HOLDERS)
  23. @SystemApi
  24. public void addRoleHolderAsUser(@NonNull String roleName, @NonNull String packageName,
  25. @ManageHoldersFlags int flags, @NonNull UserHandle user,
  26. @CallbackExecutor @NonNull Executor executor, @NonNull Consumer<Boolean> callback) {
  27. Preconditions.checkStringNotEmpty(roleName, "roleName cannot be null or empty");
  28. Preconditions.checkStringNotEmpty(packageName, "packageName cannot be null or empty");
  29. Objects.requireNonNull(user, "user cannot be null");
  30. Objects.requireNonNull(executor, "executor cannot be null");
  31. Objects.requireNonNull(callback, "callback cannot be null");
  32. try {
  33. mService.addRoleHolderAsUser(roleName, packageName, flags, user.getIdentifier(),
  34. createRemoteCallback(executor, callback));
  35. } catch (RemoteException e) {
  36. throw e.rethrowFromSystemServer();
  37. }
  38. }

打印logcat日志如下所示

  1. 2024-05-14 01:18:43.314 1653-1653 RoleManager pid-1653 D Package added as role holder, role: android.app.role.HOME, package: com.android.launcher3
  2. 2024-05-14 01:47:11.673 2854-23939 RoleContro...erviceImpl com.android.permissioncontroller I Package is already a role holder, package: com.android.launcher3, role: android.app.role.HOME
  3. 2024-05-14 01:47:11.674 1653-1653 RoleManager pid-1653 D Package added as role holder, role: android.app.role.HOME, package: com.android.launcher3
  4. 2024-05-14 01:18:43.319 2854-2854 DefaultApp...ragment ZM com.android.permissioncontroller E key=app.olauncher.debugtitle=Olauncher
  5. 2024-05-14 01:18:43.324 2854-2854 DefaultApp...ragment ZM com.android.permissioncontroller E key=com.android.launcher3title=Quickstep
  6. 2024-05-14 01:18:43.332 2854-2854 DefaultApp...ragment ZM com.android.permissioncontroller E key=app.olauncher.debugtitle=Olauncher
  7. 2024-05-14 01:18:43.338 2854-2854 DefaultApp...ragment ZM com.android.permissioncontroller E key=com.android.launcher3title=Quickstep
  8. 2024-05-14 01:47:10.880 2854-2854 DefaultApp...ragment ZM com.android.permissioncontroller E key=app.olauncher.debugtitle=Olauncher
  9. 2024-05-14 01:47:10.885 2854-2854 DefaultApp...ragment ZM com.android.permissioncontroller E key=com.android.launcher3title=Quickstep

9、代码路径 packages/modules/Permission/PermissionController/src/com/android/permissioncontroller/role/ui/ManageRoleHolderStateLiveData.java

10、代码路径frameworks\base\services\core\java\com/android\server\pm\PackageManagerShellCommand.java

  1. private int runSetHomeActivity() {
  2. final PrintWriter pw = getOutPrintWriter();
  3. int userId = UserHandle.USER_SYSTEM;
  4. String opt;
  5. while ((opt = getNextOption()) != null) {
  6. switch (opt) {
  7. case "--user":
  8. userId = UserHandle.parseUserArg(getNextArgRequired());
  9. break;
  10. default:
  11. pw.println("Error: Unknown option: " + opt);
  12. return 1;
  13. }
  14. }
  15. String pkgName;
  16. String component = getNextArg();
  17. if (component.indexOf('/') < 0) {
  18. // No component specified, so assume it's just a package name.
  19. pkgName = component;
  20. } else {
  21. ComponentName componentName =
  22. component != null ? ComponentName.unflattenFromString(component) : null;
  23. if (componentName == null) {
  24. pw.println("Error: invalid component name");
  25. return 1;
  26. }
  27. pkgName = componentName.getPackageName();
  28. }
  29. final int translatedUserId =
  30. translateUserId(userId, UserHandle.USER_NULL, "runSetHomeActivity");
  31. final CompletableFuture<Boolean> future = new CompletableFuture<>();
  32. try {
  33. RoleManager roleManager = mContext.getSystemService(RoleManager.class);
  34. roleManager.addRoleHolderAsUser(RoleManager.ROLE_HOME, pkgName, 0,
  35. UserHandle.of(translatedUserId), FgThread.getExecutor(), future::complete);
  36. boolean success = future.get();
  37. if (success) {
  38. pw.println("Success");
  39. return 0;
  40. } else {
  41. pw.println("Error: Failed to set default home.");
  42. return 1;
  43. }
  44. } catch (Exception e) {
  45. pw.println(e.toString());
  46. return 1;
  47. }
  48. }

11、最后可以把这些代码添加自己自定义系统服务AIDL接口 ,然后在Android.bp中添加源码编译路径(不知道怎么添加AIDL源码编译路径看我之前这篇文章高通 Android 12 源码编译aidl接口_安卓12 怎么写aidl-CSDN博客

12、在自己app应用调用通过 如下代码 进行设置即可(Process导入android.os包切记哈)

  1. /**
  2. * 设置当前Launcher
  3. *
  4. * @param packageName 传入第三方launcher包名
  5. */
  6. public void setCurrentLauncher(String packageName) {
  7. setRoleHolderAsUser(RoleManager.ROLE_HOME, packageName, 0, Process.myUserHandle(), mContext);
  8. }

13、最后别忘记如果你是app调用代码的时候记得加系统签名哈 AndroidManifest.xml中 ,否则也不会生效。

 android:sharedUserId="android.uid.system"

到这里基本结束了,转载请注明出处高通Android 11/12/13 通过包名设置默认launcher-CSDN博客,谢谢!

补充Android 8.1 /9.0/10 设置默认Launhcer方法,在ResolveActivity中onCreate方法添加 ,代码示例如下所示

  1. private void setDefaultLauncher(){
  2. // 只需要修改此处即可
  3. String defaultlauncherpckname = "xxx.xxx.xxx.xxx";
  4. PackageManager mPm = mContext.getPackageManager();
  5. Intent mIntent = new Intent();
  6. mIntent.setAction(Intent.ACTION_MAIN);
  7. mIntent.addCategory(Intent.CATEGORY_HOME);
  8. List<ResolveInfo> mList = mPm.queryIntentActivities(mIntent, 0);
  9. ComponentName[] mHomeComponentSet = new ComponentName[mList.size()];
  10. ComponentName newHome = null;
  11. for (int i = 0; i < mList.size(); i++) {
  12. ActivityInfo info = mList.get(i).activityInfo;
  13. ComponentName componentName = new ComponentName(info.packageName, info.name);
  14. mHomeComponentSet[i] = componentName;
  15. if (info.packageName.equals(defaultlauncherpckname)) {
  16. newHome = componentName;
  17. }
  18. }
  19. if (newHome != null) {
  20. IntentFilter mHomeFilter = new IntentFilter();
  21. mHomeFilter.addAction(Intent.ACTION_MAIN);
  22. mHomeFilter.addCategory(Intent.CATEGORY_HOME);
  23. mHomeFilter.addCategory(Intent.CATEGORY_DEFAULT);
  24. // Android8.1以后弃用了源码中的方法,如果依旧用会报错(笔者没办法调用老式)
  25. mPm.replacePreferredActivity(mHomeFilter, IntentFilter.MATCH_CATEGORY_EMPTY, mHomeComponentSet, newHome);
  26. }
  27. }
  28. startHomeActivityLocked()方法中调用setDefaultLauncher即可

感谢

Android R设置默认桌面_setroleholderasuser-CSDN博客

Android10.0(Q) 默认应用设置(电话、短信、浏览器、主屏幕应用)_android.app.role.browser-CSDN博客

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/787721
推荐阅读
相关标签
  

闽ICP备14008679号