Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android event listener for app lifecycle

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?

like image 878
Demai Ni Avatar asked Apr 16 '13 20:04

Demai Ni


2 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.

like image 154
CommonsWare Avatar answered Oct 08 '22 02:10

CommonsWare


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

like image 20
Faisal Naseer Avatar answered Oct 08 '22 01:10

Faisal Naseer