Consider this code snippet that prompts the user to rate the app on the market:
private void backToMainActivity() {
Intent i = new Intent(mActivity, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mActivity.startActivity(i);
mActivity.finish();
}
...
if (mRateToast.leftClicked(x, y)) {
setRate(true);
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + GameGlobals.PACKAGE_NAME));
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET | Intent.FLAG_ACTIVITY_NEW_TASK);
mActivity.startActivity(i);
backToMainActivity();
} else if (mRateToast.rightClicked(x, y)) {
setRate(false);
backToMainActivity();
}
What this does is detect what button was pressed (Rate or Later), set a flag accordingly and run the market app if needed. No matter which button is pressed, I want to return to the main menu (this is a game activity, 1 activity away from the main menu activity).
On Android 4.1, this works fine – the market opens to the app’s page, and on return from the market, I am on the main menu. On android <= 2.3, the market does not open, I am just returned directly to the main menu. It does, however, open if I comment the i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); in the backToMainActivity method. This causes other problems though, such as the back button going back to the wrong activity instead of exiting the app, so is not a solution.
How can I run the market, return to main menu and have the main menu activity be at the top of the activity stack?
Note: I haven’t tried it, but removing the finish is also not really an option. My game activity can also be started by external applications directly, and in that case, if I remove the finish call, for some reason CLEAR_TOP will not work, and pressing the back button on the main menu activity will return to the game activity instead of exiting the application.
I solved this by removing
Intent.FLAG_ACTIVITY_NEW_TASKand usingstartActivityForResultas described by MoshErsan in his answer. Apparently starting the market as a new task does not play well withCLEAR_TOPin android <= 2.3.If someone can explain why the original approach wasn’t working or offer a better solution, I will accept that answer in one or two days, if not I will accept mine.