How to return to the latest launched activity when re-launching application after pressing HOME?

后端 未结 6 1696
臣服心动
臣服心动 2020-12-01 08:15

Familiar scenario: I have a Main activity that launches a Game activity when a button is pressed. If the user presses HOME, and then launches my applicatio

6条回答
  •  离开以前
    2020-12-01 08:46

    I would highly recommend using isTaskRoot to check whether the activity should be finished instead of the FLAG_ACTIVITY_BROUGHT_TO_FRONT flag.

    I liked Sachin's answer, but sometimes it gave me false-positives and I would finish the activity when I shouldn't. The reliable way I found to reproduce such a false positive is:

    1. Launch the app from homescreen
    2. Press home
    3. Launched the app from home screen again
    4. Press "back" to return to home screen
    5. Returned to the app from "recent apps"

    I started looking for ways to inspect my task's activity backstack and found answers using ActivityManager. This seemed like it could work, but this answer pointed out the existence of isTaskRoot, which is a simple, elegant way of detecting this which doesn't give false positives, doesn't require a special permission and doesn't use methods that docuemtation says are intended for debugging and task management apps and which are unsupported for this type of use.

提交回复
热议问题