Checking if an Android application is running in the background

前端 未结 30 2797
无人共我
无人共我 2020-11-21 06:19

By background, I mean none of the application\'s activities are currently visible to the user?

30条回答
  •  鱼传尺愫
    2020-11-21 07:13

    See the comment in the onActivityDestroyed function.

    Works with SDK target version 14> :

    import android.app.Activity;
    import android.app.Application;
    import android.os.Bundle;
    import android.util.Log;
    
    public class AppLifecycleHandler implements Application.ActivityLifecycleCallbacks {
    
        public static int active = 0;
    
        @Override
        public void onActivityStopped(Activity activity) {
            Log.i("Tracking Activity Stopped", activity.getLocalClassName());
            active--;
        }
    
        @Override
        public void onActivityStarted(Activity activity) {
            Log.i("Tracking Activity Started", activity.getLocalClassName());
            active++;
        }
    
        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            Log.i("Tracking Activity SaveInstanceState", activity.getLocalClassName());
        }
    
        @Override
        public void onActivityResumed(Activity activity) {
            Log.i("Tracking Activity Resumed", activity.getLocalClassName());
            active++;
        }
    
        @Override
        public void onActivityPaused(Activity activity) {
            Log.i("Tracking Activity Paused", activity.getLocalClassName());
            active--;
        }
    
        @Override
        public void onActivityDestroyed(Activity activity) {
            Log.i("Tracking Activity Destroyed", activity.getLocalClassName());
            active--;
    
            // if active var here ever becomes zero, the app is closed or in background
            if(active == 0){
                ...
            }
    
        }
    
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            Log.i("Tracking Activity Created", activity.getLocalClassName());
            active++;
        }
    }
    

提交回复
热议问题