How do I use PackageManager.addPreferredActivity()?

感情迁移 提交于 2019-11-28 05:02:05
a2ronus

@afonseca: I was dealing with the same problem. Thanks for the code, I used it to start with. Also thanks Shimon. I merged his answer into mine. I've got the code working (on 1.6 and 2.1 update 1). It has been adjusted a little bit, but the 2 main change seem to be Shimons suggestion and: ".Launcher" was changed to "com.android.launcher.Launcher". The working code is posted below.

Ciao, a2ronus

PackageManager pm = getPackageManager();

IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.MAIN");
filter.addCategory("android.intent.category.HOME");
filter.addCategory("android.intent.category.DEFAULT");

Context context = getApplicationContext();
ComponentName component = new ComponentName(context.getPackageName(), TestReplaceHomeAppActivity.class.getName());

ComponentName[] components = new ComponentName[] {new ComponentName("com.android.launcher", "com.android.launcher.Launcher"), component};

pm.clearPackagePreferredActivities("com.android.launcher");
pm.addPreferredActivity(filter, IntentFilter.MATCH_CATEGORY_EMPTY, components, component);

This answer may come a little late but API docs says for clearPackagePreferredActivities:

An application can only clear its own package(s).

So, I think that in "restoring the mapping" the only you can do is something like:

getPackageManager().clearPackagePreferredActivities(getPackageName());

and so clearing the default setting for HOME screen.

Shimon Shnitzer

This seems to work for me if I initialize the components array to ALL HOME apps on the device:

ComponentName[] components = new ComponentName[]
{
   new ComponentName("com.intuitiveui.android", "com.intuitiveui.android.Friday"),
   new ComponentName("com.android.launcher2","com.android.launcher2.Launcher")
};

My problem is how do I fill this dynamically.

addPreferredActivity does not work anymore in 2.2, clearPackagePreferredActivities still works but you can only clear preference for the package you run this on.

there are a lot of threads on android google groups about this problem and google's official position (for now) not to provide you with methods to overide user's preferences.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!