Detect When Application Goes to Background or Become Active From Background.
Apr 15, 2021
This is Android equivalent to iOS applicationDidBecomeActive or applicationDidEnterBackground. However the same implementation in Android is much more complicated. Here is how you can do this properly.
This is essentially equivalent to iOS applicationDidBecomeActive or applicationDidEnterBackground in Android. However the same implementation in Android is much more complicated. Here is how you can do this properly.
App Lifecycle
On Android we use the LifecycleObserver from androidx.lifecycle.lifecycleObserver. First create an object that implements LifecycleObserver in your project. For example:
Now we will host an instance of the above object inside your app application object. Note that your application will implement the AppLifecycleCallback
1
private AppLifecycleListener mAppLifecycleListener = new AppLifecycleListener(this);
After that, register it inside your application onCreate.
Now if you run the app, and bring the app to background, or active your app, those callback function will be triggered inside your application object. However, most of times, you will want activity to handle those actions. How to reach to your activity?
Activity Lifecycle
My solution is to implement Application.ActivityLifecycleCallbacks to host a topmost activity within the reach of the application object.
This is my listener. I only need to get access to the top most activity so all I need to monitor is the onActivityResumed function.
Now we will need to put this as a reference in the application object, and register the callback in the onCreate function.
1 2 3
private AppActivityLifecycleCallbacks mActivityLifecycleCallbacks = new AppActivityLifecycleCallbacks(); // Inside function onCreate: registerActivityLifecycleCallbacks(mActivityLifecycleCallbacks)
Now, in the Application callbacks, we can check the top most activity if they implements AppLifeCycleCallback, if yes, then redirect the call, if not, then ignore. Then we will just need to implement AppLifeCycleCallback in the Activity that we want to handle the event.
1 2 3 4 5 6 7 8
// For example under XXApplication.java @Override publicvoidonAppBecomeActive(){ Activity onTopActivity = mActivityLifecycleCallbacks.onTopActivity; if (onTopActivity instanceof AppLifecycleCallback) { ((AppLifecycleCallback) onTopActivity).onAppBecomeActive(); } }
Now, this is my application class, which includes both app lifecycle and activity lifecycle.
//region Implement AppLifecycleCallback @Override publicvoidonAppBecomeActive(){ // Do anything you want to do when app is active, for example: myFragment.showTint().isActive().... } //endregion }