0

Suppose I have an Activity named ActivityA and another Activity named ActivityB. In each one I have a button that opens another Activity when it is clicked. I want to do following work when button is clicked:

check if there is an existing type of the target Activity in the activity back-stack or not, if there is, bring that Activity to the top and if not create new Intent and then go to that Activity.
How can I implement this?

Thanks.

7
  • try add launch mode in the manifest for single instance Commented Nov 26, 2019 at 7:49
  • Yes for Zach's comment, and the doc is here
    – Weekend
    Commented Nov 26, 2019 at 8:03
  • @ZachBublil that does not solve all my problem. I want to hold another activity in the back-stack and just want to bring target activity to front.
    – Test Test
    Commented Nov 26, 2019 at 10:07
  • @Weekend please read my comment.
    – Test Test
    Commented Nov 26, 2019 at 10:08
  • 1
    As I said, try the launch mode option in the AndroidManifest. In short, it defines how your activity would be launched - single instance makes your app bring the activity to front if the back stack is already has an instance of this activity or create an instance if not. Commented Nov 26, 2019 at 10:10

1 Answer 1

1

Simple.

Intent intent = new Intent(this, TargetActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);

This does exactly what you want. If there is already an instance of TargetActivity in the task stack, that instance will be rearranged and brought to the top (front) of the stack. If there is no existing instance of TargetActivity, Android will create a new instance and put that on the top of the stack.

Not the answer you're looking for? Browse other questions tagged or ask your own question.