Search code examples
androidandroid-activityandroid-lifecycleonpause

How to differentiate between different causes that an Activity's onPause() is called?


I need to figure out why my Activity's onPause/onStop is called, specifically, whether another Activity (especially from another app) has replaced it, or not.

I can think of a few reasons why my Activity may be paused/stopped, as well as a few Activity life cycle methods (onUserLeaveHint, onBackPressed , onPause, onStop, onDestroy, isFinishing) that may help me in differentiating them, but so far I haven't been able to complete it. Here they are:

Turn off display:
onPause - isFinishing FALSE
onStop - isFinishing FALSE

Back button:
onBackPressed - isFinishing TRUE
onPause - isFinishing TRUE
onStop - isFinishing TRUE
onDestroy - isFinishing TRUE

Home button:
onUserLeaveHint - isFinishing FALSE
onPause - isFinishing FALSE
onStop - isFinishing FALSE

Task switcher:
onUserLeaveHint - isFinishing FALSE
onPause - isFinishing FALSE
onStop - isFinishing FALSE

New Activity:
onUserLeaveHint - isFinishing FALSE
onPause - isFinishing FALSE
onStop - isFinishing FALSE

Notably missing is when Android low memory killer kills my Activity. I haven't been able to reproduce that yet hence no results.

So, I'm able to differentiate when the back button is pressed, and when the display is turned off. However, pressing the home button, task switcher and launching a new activity are identical programmatically to me. How do I differentiate between them?


Solution

  • OK I ended up doing a few things to differentiate the various cases:

    Set a flag in onBackPressed() to detect the back button Check the new foreground app in the service to detect the launcher and task switcher. In all other cases of a new foreground app, inform the user.