本文参考这位哥们: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); }}
原文地址:https://www.cnblogs.com/Oldz/p/12096935.html
时间: 2024-11-07 17:03:46