https://stackoverflow.com/questions/4414171
這問題歷經十年
解決方案也有變化...
比較優雅的做法是使用:
https://developer.android.com/reference/android/arch/lifecycle/ProcessLifecycleOwner.html
ProcessLifecycleOwner
will dispatchON_START
,ON_RESUME
events, as a first activity moves through these events.ON_PAUSE
,ON_STOP
, events will be dispatched with a delay after a last activity passed through them. This delay is long enough to guarantee thatProcessLifecycleOwner
won't send any events if activities are destroyed and recreated due to a configuration change.
It is useful for use cases where you would like to react on your app coming to the foreground or going to the background and you don't need a milliseconds accuracy in receiving lifecycle events.
https://stackoverflow.com/questions/4414171/#answer-44461605
According to source code, current delay value is
700ms
中文說明:
ProcessLifecycleOwner 判断 Android 应用程序前后台切换
- Single Activity architecture
- ActivityLifecycleCallback
- LifecycleObserver and ProcessLifecycleOwner
詳細: Foreground or Background ? - Know how to detect your application’s visibility, in Android