Android: How to control the home button

三世轮回 提交于 2019-11-30 22:04:43

Can I achieve this by making my application itself the launcher? How can I then get back to the original launcher upon the home, back, home sequence? It seems that this goes deep into the innards of Android, huh?

Yes. Not too deep into the innards. You can manually start a launcher by specifying the component, note that this may vary from device to device and user to user, if you're just using this privately you could hard code it, but if you release it you must allow the user to specify their real home app.

/* This should come from a preference that let's the user select an activity that can handle the HOME intent */
String packageName = "com.android.launcher";
String packageClass = "com.android.launcher2.Launcher";

Intent home_intent = new Intent(Intent.ACTION_MAIN);
home_intent.addCategory(Intent.CATEGORY_HOME);
home_intent.setComponent(new ComponentName(packageName, packageClass));
home_intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
/* Here you should catch the exception when the launcher has been uninstalled, and let the user save themselves by opening the Market or an app list or something. Users sometimes use root apps to uninstall the system launcher, so your fake launcher is all that is left. Might as well give the poor user a hand. */
startActivity(home_intent);

Detecting home/back/home is a bit awkard because home won't come as a onKeyEvent but instead as a new intent. Simply long-pressing the back button then display a prompt is probably a safe/good approach.

The Home button cannot be overriden. You can write an application that responds to the home intent (that's what a launcher does) but that's all.

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