Skip to content

Instantly share code, notes, and snippets.

@tw-Frey
Last active November 16, 2021 09:45
Show Gist options
  • Save tw-Frey/4da25b68a79175e85748df1e0699921b to your computer and use it in GitHub Desktop.
Save tw-Frey/4da25b68a79175e85748df1e0699921b to your computer and use it in GitHub Desktop.
How to detect when an Android app goes to the background and come back to the foreground... (十年問題)

https://stackoverflow.com/questions/4414171
這問題歷經十年
解決方案也有變化...


比較優雅的做法是使用:

ProcessLifecycleOwner

https://developer.android.com/reference/android/arch/lifecycle/ProcessLifecycleOwner.html

ProcessLifecycleOwner will dispatch ON_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 that ProcessLifecycleOwner 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 应用程序前后台切换


WitWicky 歸納出三種解法 [出處]

  • Single Activity architecture
  • ActivityLifecycleCallback
  • LifecycleObserver and ProcessLifecycleOwner

詳細: Foreground or Background ? - Know how to detect your application’s visibility, in Android


1-yRFmm1aMUhvaylM3VnPoqg 參考: gist/AlexZhukovich/Analytics.kt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment