Search code examples
androidlaunchmode

Activity is creating again when i want to bring existing one to front


I've added REORDER_TO_FRONT flag to bring my existing activity to top instead of creating a new instance. But it calls onCreate method of the activity instead of onNewIntent in MainActivity. If i add launchMode="singleTop" in Menifest, then works fine. But i don't want to add singleTop because in some cases in minimized mode if user click on app icon, then app restarts instead of resuming from same place.

    Intent intent = MainActivity.newIntent(context);
    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);

Thanks


Solution

  • You just need to add the SINGLE_TOP flag to your Intent, like this:

    Intent intent = MainActivity.newIntent(context);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    

    This will remove all activities from the stack back to the existing instance of MainActivity. It will NOT create a new instance of MainActivity or call onCreate(). It will call onNewIntent() in MainActivity().