Marc's answer works great, except in my case where my main activity has a launchMode of singleTop. Once I run this intent and then navigate to new Activities and press the home button on the device, then launch my app again from the app icon, I end up creating a new instance of the main Activity, with my previous activity on the back stack.
According to this question it's because the intents don't match. Looking at adb dumpsys activity
, I see that from my standard android launcher, the package is null, whereas when I do as Marc suggests, the intent package is the name of my package. This difference causes them to not match and to start a new instance when the app icon is tapped again and the main activity isn't on top.
However, on other launchers, like on Kindle, the package is set on the launcher intent, so I needed a generic way to handle launchers. I added static methods like such:
static boolean mIsLaunchIntentPackageNull = true;
public static boolean isLaunchIntent(Intent i) {
if (Intent.ACTION_MAIN.equals(i.getAction()) && i.getCategories() != null
&& i.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
return true;
}
return false;
}
public static void handleLaunchIntent(Intent i) {
if (isLaunchIntent(i)) {
if (i.getPackage() != null) {
mIsLaunchIntentPackageNull = false;
}
else {
mIsLaunchIntentPackageNull = true;
}
}
}
with a go home mechanism like this:
Intent intentHome = appContext.getPackageManager()
.getLaunchIntentForPackage( appContext.getPackageName());
intentHome.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// need to match launcher intent exactly to avoid duplicate activities in stack
if (mIsLaunchIntentPackageNull) {
intentHome.setPackage(null);
}
appContext.startActivity(intentHome);
then in the main activity defined in my manifest, I added this line:
public void onCreate(Bundle savedInstanceState) {
[class from above].handleLaunchIntent(getIntent());
this works for me on kindle and my phone, and lets me properly reset the app w/o adding another instance of the main activity.