- 需求:开机启动定制launcher,不删除默认launcher
想要替换桌面launcher,首先你要在自己的应用中添加home属性
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
添加完之后运行,会弹出home选择界面,之前写过一篇文章修改默认启动项launcher(一),那篇文章中是通过跳过这个选择界面,根据应用包名启动默认launcher,当应用不存在启动系统launcher。这个方法有一定的局限性,如果应用不存在,其他应用就算添加了home属性,还是会弹出home选择界面。本篇文章优化通过定制 Intent.CATEGORY_HOME 来实现默认启动定制launcher。
1.自定义CATEGORY_HOME
- 源码位置:frameworks/base/core/java/android/content/Intent.java
public static final String CUSTOM_CATEGORY_HOME = "android.intent.category.custom.HOME";
2.开机启动时添加定制的category
- 源码位置:frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
/**
* add for custom launcher
*/
private Intent getCustomHomeIntent() {
Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
intent.setComponent(mTopComponent);
if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
intent.addCategory(Intent.CUSTOM_CATEGORY_HOME);
}
return intent;
}
boolean startHomeActivityLocked(int userId, String reason) {
if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL && mTopAction == null){
// error message and don't try to start anything.
return false;
}
// add for custom launcher
/* Intent intent = getHomeIntent();
ActivityInfo aInfo = resolveActivityInfo(intent, STOCK_PM_FLAGS, userId); */
Intent intent = getCustomHomeIntent();
ActivityInfo aInfo = resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
if(aInfo == null) {
intent = getHomeIntent();
//Slog.v("custom","getHomeIntent");
aInfo = resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
}
// end
....
}
3.如果没有应用携带定制的category,移除category
- 源码位置:frameworks/base/core/java/com/android/internal/app/ResolverActivity.java
private void rebuildList() {
...
if (mBaseResolveList != null) {
currentResolveList = mOrigResolveList = new ArrayList<>();
addResolveListDedupe(currentResolveList, getTargetIntent(), mBaseResolveList)
} else {
// add for custom launcher
getTargetIntent().addCategory(Intent.CUSTOM_CATEGORY_HOME);
final boolean shouldGetResolvedFilter = shouldGetResolvedFilter();
final boolean shouldGetActivityMetadata = shouldGetActivityMetadata();
// add for custom launcher
final List<ResolveInfo> tmp = mPm.queryIntentActivities(getTargetIntent(),
PackageManager.MATCH_DEFAULT_ONLY
| (shouldGetResolvedFilter ? PackageManager.GET_RESOLVED_FILTER : 0)
| (shouldGetActivityMetadata ? PackageManager.GET_META_DATA : 0));
if(tmp == null || tmp.size() == 0){
getTargetIntent().removeCategory(Intent.CUSTOM_CATEGORY_HOME);
//Log.d("custom","removeCategory");
}
// end
4.应用中添加自定义category
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.custom.HOME"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
通过自定义category_home实现默认启动项launcher的修改。