I'm building a launcher/home screen replacement app and I've noticed all launchers allow the user to press home to go to the first screen of the launcher. So it's obviously possible to listen to the home key for home replacement apps but I haven't been able to figure out how.
How can I listen to the home key and trigger setCurrentItem(0) when the user presses home while inside my launcher?
EDIT
I have two options until now:
@Override
public void onPause() {
super.onPause();
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
if(!this.isFinishing())
{
if (sharedPrefs.getBoolean("user_called", false))
{
// Si fue por una llamada del usuario eliminar bandera y no hacer nada
Utils.setUserCalled(getApplicationContext(), false);
}
else
{
mPager.setCurrentItem(0);
}
}
}
The other method is this:
Boolean appState = false;
@Override
public void onPause() {
super.onPause();
appState = false;
}
@Override
public void onResume() {
super.onResume();
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
if(!appState)
{
if (sharedPrefs.getBoolean("user_called", false))
{
// Si fue por una llamada del usuario eliminar bandera y no hacer nada
Utils.setUserCalled(getApplicationContext(), false);
}
else
{
mPager.setCurrentItem(0);
}
}
}
Both use a flag callsed user_called to know if the user started a call. My problem right now is that both methods fail when the phone rings. Is there a way to filter these cases?
You cannot listen to home button press since it is a system event and is not delivered to the applications. That is described in the documentation here and also can be seen from Android codes here. The idea behind is simple - you should not be able to write an app which will hijack the phone. You can "break" the back button functionality, but not the home button functionality.
Now what the third-party launchers are usually doing is first of all declaring the launcher activity launch mode as singleInstance in manifest: android:launchMode="singleInstance"
. Then, in addition to overriding the onCreate()
you also override onNewIntent()
. It is usually called instead of onCreate()
when the activity is already running but someone fired an intent to start it again. In case of a launcher it will be called when your launcher is already running but system fires an intent to launch it because the user pressed the home button. In that function you can go to your default 'home' page.