需求:Android13 动态切换默认laucnher
废话不多说:直接上代码
package com.taide.launcher.util;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.text.TextUtils;
import java.util.List;
public class LauncherUtils {
private static List<ResolveInfo> getResolveInfoList(Context context) {
PackageManager pm = context.getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_HOME);
intent.addCategory(Intent.CATEGORY_DEFAULT);
return pm.queryIntentActivities(intent, 0);
}
private static ResolveInfo getCurrentLauncher(Context context) {
PackageManager pm = context.getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_HOME);
intent.addCategory(Intent.CATEGORY_DEFAULT);
return pm.resolveActivity(intent, 0);
}
public static void setDefaultLauncher(Context context, String packageName) {
PackageManager pm = context.getPackageManager();
ResolveInfo currentLauncher = getCurrentLauncher(context);
List<ResolveInfo> packageInfos = getResolveInfoList(context);
ResolveInfo futureLauncher = null;
for (ResolveInfo ri : packageInfos) {
if (!TextUtils.isEmpty(ri.activityInfo.packageName) && !TextUtils.isEmpty(packageName)
&& TextUtils.equals(ri.activityInfo.packageName, packageName)) {
futureLauncher = ri;
}
}
if (futureLauncher == null) {
return;
}
pm.clearPackagePreferredActivities(currentLauncher.activityInfo.packageName);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_MAIN);
intentFilter.addCategory(Intent.CATEGORY_HOME);
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
ComponentName componentName = new ComponentName(futureLauncher.activityInfo.packageName,
futureLauncher.activityInfo.name);
ComponentName[] componentNames = new ComponentName[packageInfos.size()];
int defaultMatch = 0;
for (int i = 0; i < packageInfos.size(); i++) {
ResolveInfo resolveInfo = packageInfos.get(i);
componentNames[i] = new ComponentName(resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name);
if (defaultMatch < resolveInfo.match) {
defaultMatch = resolveInfo.match;
}
}
pm.clearPackagePreferredActivities(currentLauncher.activityInfo.packageName);
pm.addPreferredActivity(intentFilter, defaultMatch, componentNames, componentName);
}
}