Android R设置默认桌面
Posted 虫师魁拔
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android R设置默认桌面相关的知识,希望对你有一定的参考价值。
一、launcher 启动过程
首先看下系统启动 Launcher 过程,主要涉及以下类和方法:
AMS :
systemReady -> mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
ActivityTaskManagerInternal :
startHomeOnAllDisplays -> mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
RootWindowContainer :
startHomeOnDisplay -> startHomeOnTaskDisplayArea -> mService.getActivityStartController().startHomeActivity(homeIntent, aInfo, myReason, taskDisplayArea);
ActivityStartController 中按照一般 activity 正常的启动。
二、修改默认 launcher 方案
设置默认应用方式有两种:
1、通过 RoleManager 接口设置
setRoleHolderAsUser(RoleManager.ROLE_HOME, "com.android.launcher3", 0, Process.myUserHandle(), this);
public void setRoleHolderAsUser(String roleName, String packageName,
int flags, UserHandle user, Context context) {
RoleManager roleManager = (RoleManager)context.getSystemService(Context.ROLE_SERVICE);
Executor executor = context.getMainExecutor();
Consumer<Boolean> callback = successful -> {
if (successful) {
Log.d(TAG, "Package added as role holder, role: " + roleName + ", package: " + packageName);
} else {
Log.d(TAG, "Failed to add package as role holder, role: " + roleName + ", package: "
+ packageName);
}
};
roleManager.addRoleHolderAsUser(roleName, packageName, flags, user, executor, callback);
}
这个是异步设置,需要在回调函数中进行监听判断。
2、通过 PackageManager 接口设置
PackageManager pm = getPackageManager();
Intent queryIntent = new Intent();
queryIntent.addCategory(Intent.CATEGORY_HOME);
queryIntent.setAction(Intent.ACTION_MAIN);
List<ResolveInfo> homeActivities = pm.queryIntentActivities(queryIntent, 0);
if(homeActivities == null) {
return;
}
ComponentName defaultLauncher = new ComponentName("com.android.launcher3",
"com.android.launcher3.Launcher");
int activityNum = homeActivities.size();
ComponentName[] set = new ComponentName[activityNum];
int defaultMatch = -1;
for(int i = 0; i < activityNum; i++){
ResolveInfo info = homeActivities.get(i);
set[i] = new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
if("com.android.launcher3.Launcher".equals(info.activityInfo.name)
&& "com.android.launcher3".equals(info.activityInfo.packageName)){
defaultMatch = info.match;
}
}
//if Launcher3 is not found, do not set anything
if(defaultMatch == -1){
return;
}
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MAIN);
filter.addCategory(Intent.CATEGORY_HOME);
filter.addCategory(Intent.CATEGORY_DEFAULT);
pm.addPreferredActivity(filter, defaultMatch, set, defaultLauncher);
这种方式需要注意 queryIntentActivities 查询不全的情况,参照上一篇记录说明。
第一种方案更适合 APP 运行中动态设置和监听。第二种适合系统默认设置,在AMS或者开机向导种添加此段代码。
以上是关于Android R设置默认桌面的主要内容,如果未能解决你的问题,请参考以下文章