首页 > 代码库 > 自定义Launcher设为默认应用

自定义Launcher设为默认应用

核心代码:

....
// launcher应用中包含的xml配置
		String action = Intent.ACTION_MAIN;
		String category1 = Intent.CATEGORY_HOME;
		String category2 = Intent.CATEGORY_DEFAULT;

		IntentFilter filter = new IntentFilter();
		filter.addAction(action);
		filter.addCategory(category1);
		filter.addCategory(category2);
		
		// 创建默认应用componentName,这里为本应用
		ComponentName component = new ComponentName(getApplicationContext().getPackageName(), MainActivity.class.getName());
		
		Intent intent = new Intent();
		intent.setAction(action);
		intent.addCategory(category1);

		PackageManager pm = getPackageManager();
		// 使用PackageManager查找action为Intent.ACTION_MAIN、category为Intent.CATEGORY_HOME的所有应用包
		List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.GET_INTENT_FILTERS);
		ComponentName[] comNames = new ComponentName[list.size()];
		
		int size = list.size();
		for(int i = 0; i < size ; i++){
			ActivityInfo activityInfo = list.get(i).activityInfo;
			String pckName = activityInfo.packageName;
			String clsName = activityInfo.name;
			// 循环清除原有的默认应用设置
			pm.clearPackagePreferredActivities(pckName);
			ComponentName cn = new ComponentName(pckName, clsName);
			comNames[i] = cn;
		}
		/*
		 *  设置默认应用,对华为Link+源码分析,最终设置参数持久化到/data/system/users/0/package-restrictions.xml 中
		 *  
		 *  addPreferredActivity 需要 android.permission.SET_PREFERRED_APPLICATIONS权限,该权限需要使用signapk签名 
		 */
		pm.addPreferredActivity(filter, IntentFilter.MATCH_CATEGORY_EMPTY, comNames, component);
...

signapk签名可参照

Android apk 获取系统权限的方式