androidandroid-lifecyclebackground-foreground

How to hook into Android Application lifecycle?


Android supports hooking into the Activity lifecycle through Application.ActivityLifecycleCallbacks but I couldn't find a way to easily hook into the Application one. Why isn't there a similar interface for the Application lifecycle?

I want to know if an app is in background/foreground and I don't want to do the count manually (feasible using the Application.ActivityLifecycleCallbacks).

I'm developing an Android library and one of the use cases requires knowing if the app which includes the lib is in background/foreground.

I saw that there is an ApplicationLifecycleCallback interface available in the android.support.test.runner.lifecycle package (only for testing). Why not exposing something similar within the android.app package as Application.ActivityLifecycleCallbacks?

How to accomplish my use case? How would you implement it?

Any hints/ideas/workarounds would be more than welcome. Thanks a lot!


Solution

  • I want to know if an app is in background/foreground and I don't want to do the count manually (feasible using the Application.ActivityLifecycleCallbacks).

    If that is how you are defining "Application lifecycle", use ProcessLifecycleOwner from the Architecture Components.