码迷,mamicode.com
首页 > 移动开发 > 详细

Android前后台切换的监听

时间:2019-12-25 16:05:39      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:err   resume   callbacks   blank   ack   切换   return   create   ati   

 本文参考这位哥们:https://juejin.im/post/5b87f409e51d4538b0640f58

首先写两个类文件ActivityLifecycleCallbacksAdapter、LifecycleHelper :

public class ActivityLifecycleCallbacksAdapter implements Application.ActivityLifecycleCallbacks {

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

    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

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

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }
}

 

public class LifecycleHelper {

    // 监听切换到前台
    private int rusumeActivityCount = 0;

    private static LifecycleHelper lifecycleHelper;

    public static LifecycleHelper getInstance() {
        if (lifecycleHelper == null) {
            lifecycleHelper = new LifecycleHelper();
        }
        return lifecycleHelper;
    }

    public void register(Application application) {
        if (application != null)
            application.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacksAdapter() {
                @Override
                public void onActivityStarted(Activity activity) {
                    if (rusumeActivityCount++ == 0) {
                        // 执行切换到前台的逻辑
                        Lig.i("后台 --> 前台");
                        FloatWindowUtil.hideShow();
                        // ... 使用EventBus传递数据
                    }
                }

                @Override
                public void onActivityStopped(Activity activity) {
                    if (--rusumeActivityCount == 0) {
                        // 执行切换到后台的逻辑
                        Lig.i("前台 --> 后台");
                        // ... 使用EventBus传递数据
                    }
                }
            });
    }

}

在MyApplication.java中进行注册:

public class MyApplication extends Application {
@Override public void onCreate() {super.onCreate();//前后台切换的监听 LifecycleHelper.getInstance().register(this); }
}

 

Android前后台切换的监听

标签:err   resume   callbacks   blank   ack   切换   return   create   ati   

原文地址:https://www.cnblogs.com/Oldz/p/12096935.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!