Search code examples
androidandroid-intentandroid-activityback-stack

Right intent-flags to go back to last opened activity regardless of app affiliation


In may app there is an activity "AlertActivity" that is started from a service once in a while (think of it as an alarm going off). The user can choose to interact with this alarm or cancel it, if he/she is busy. When the user cancels the activity, I finish() it and would like the user to be brought back to the activity he was currently using (not necessarily from my own app).

I first started with:

            Intent intent = new Intent(ctx, AlertActivity.class);

            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //Note that Intent.FLAG_ACTIVITY_NEW_TASK is needed in order to call startActivity without an activity context

            startActivity(intent);

Using this approach, AlertActivity finishes to the most recently used activity from my app, instead of the last opened activity from any app before the alert.

The next thing I tried was:

            Intent intent = new Intent(ctx, AlertActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);

which always finishes to the last activity that does NOT belong to my app, which is not what I want, if the user was using an activity from my app before the alert set off.

Is there any combination of Flags or any other trick at all by which the last used activity is restored after finishing the AlertActivity regardless of whether this activity belongs to my application or not?


Solution

  • <activity android:name=".AlarmActivity" android:launchMode="singleTask" android:taskAffinity="" android:excludeFromRecents="true"> </activity>

    change this code to manifest file and check the result.