Home » Android » Android event listener for app lifecycle

Android event listener for app lifecycle

Posted by: admin June 15, 2020 Leave a comment

Questions:

I am writing an Android code segment to help tracing Android event as a service tool for app developers.

For example, the main app body can be just to display ‘hello world’. My code will listen to the app event, such as onStart(), onResume(), onDestroy(), etc, and keep a trace on these events.

Certainly, the code can be inserted directly under the main activity. But that means my code will be allover the places. Is there a way, I can create an object (i.e., a listener), and only request the app developer to add 1~2 liner to use my code?

How to&Answers:

For API Level 14 and higher, you can call registerActivityLifecycleCallbacks() on the Application to set up a listener to be informed about activity lifecycle events.

Answer:

Try this Approach

public class mYApplication extends Application {

 @Override
    public void onCreate() {
        super.onCreate();
        registerActivityLifecycleCallbacks(new MyLifecycleHandler());

     }

}

MyLifecycleHandler :

public class MyLifecycleHandler implements Application.ActivityLifecycleCallbacks {
    private static int resumed;
    private static int paused;
    private static int started;
    private static int stopped;

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
    }

    @Override
    public void onActivityResumed(Activity activity) {
        ++resumed;
    }

    @Override
    public void onActivityPaused(Activity activity) {
        ++paused;
        android.util.Log.w("test", "application is in foreground: " + (resumed > paused));
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
    }

    @Override
    public void onActivityStarted(Activity activity) {
        ++started;
    }

    @Override
    public void onActivityStopped(Activity activity) {
        ++stopped;
        android.util.Log.w("test", "application is visible: " + (started > stopped));
    }

    public static boolean isApplicationVisible() {
        return started > stopped;
    }

    public static boolean isApplicationInForeground() {
        return resumed > paused;
    }


}

and then call isApplicationInForeground static method to check if application is in foreground or background