敢说敢作敢为, 无怨无恨无悔。这篇文章主要讲述Android前后台切换的监听相关的知识,希望能为你提供帮助。
本文参考这位哥们:https://juejin.im/post/5b87f409e51d4538b0640f58
【Android前后台切换的监听】首先写两个类文件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); }
}
推荐阅读
- ClassPathXmlApplicationContext源码分析
- android(APP设置以太网静态IP_简要步骤)
- 学习 APPIUM 元素定位 (JAVA)-xpath
- 30天设计–品牌案例研究
- 顶级设计师使用的10种UX可交付成果
- Framer教程(如何创建出色的交互式原型)
- 为什么初创企业需要样式指南
- 为什么要使用材料设计(权衡利弊)
- 设计过程(是客观的还是主观的())