Android前后台切换的监听
Posted 全栈工程师
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android前后台切换的监听相关的知识,希望对你有一定的参考价值。
本文参考这位哥们: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前后台切换的监听的主要内容,如果未能解决你的问题,请参考以下文章
Android Reorder Fragment Backstack