Android-App前台进程监听ActivityLifecycleCallbacks

在开发中会遇到判断 App是否是前台进程,其实方法挺多,比如RunningTask(5.0之前 )、UsageStatsManager(5.0之后适用)、RunningProcess(不能有效识别,比如三星手机)、ActivityLifecycleCallbacks,其中最有效的方法是通过ActivityLifecycleCallbacks进行监听 ,本文只介绍这种。
先了解下ActivityLifecycleCallbacks,当Activity处于各生命周期中时会走如下各方法回调

    public interface ActivityLifecycleCallbacks {
        void onActivityCreated(Activity activity, Bundle savedInstanceState);
        void onActivityStarted(Activity activity);
        void onActivityResumed(Activity activity);
        void onActivityPaused(Activity activity);
        void onActivityStopped(Activity activity);
        void onActivitySaveInstanceState(Activity activity, Bundle outState);
        void onActivityDestroyed(Activity activity);
    }

当然首先得在Application注册监听(无需做反注册操作)

      registerActivityLifecycleCallbacks(ActivityLifecycleCallbacks);

因为比较简单所以不做过多说明了,直接上使用方法
首先创建Listener实现该接口

public class AppStatusTracker implements Application.ActivityLifecycleCallbacks {
    private static AppStatusTracker tracker;
    private Application application;
    private boolean isForground;
    private int activeCount;
    private long timestamp;


    private AppStatusTracker(Application application) {
        this.application = application;
        this.application.registerActivityLifecycleCallbacks(this);
    }

    public static void init(Application application) {
        tracker = new AppStatusTracker(application);
    }

    public static AppStatusTracker getInstance() {

        if (null == tracker) {
            tracker = new AppStatusTracker(new AppContext());
        }
        return tracker;
    }

    public boolean isForground() {
        return isForground;
    }


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

    }

    @Override
    public void onActivityStarted(Activity activity) {

        if (activeCount == 0){
            timestamp = System.currentTimeMillis();
        }
        activeCount++;
    }

    @Override
    public void onActivityResumed(Activity activity) {
        isForground = true;
    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

        activeCount--;
        if (activeCount == 0) {
            isForground = false;
            timestamp = System.currentTimeMillis() - timestamp;
        }
    }

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

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }
}

然后只需在 Application 的 onCreate 中进行注册

        AppStatusTracker.init(this);

OK了,知识点不多,要了解更多可围绕 Android5.0 前台进程去搜索


参考
初识 ActivityLifecycleCallbacks

你可能感兴趣的:(Android-App前台进程监听ActivityLifecycleCallbacks)