Android Lifecycle应用生命周期全局监听(前后台,销毁等)

在Application初始化Lifecycle监听:

/*
 *Author:XingHai.Zhao
 *Purpose: Application
 */
class App : Application() {
    override fun onCreate() {
        super.onCreate()
        //初始化Lifecycle监听
        ProcessLifecycleOwner.get().lifecycle.addObserver(LifecycleChecker())
    }
}
LifecycleChecker实体类:
/*
 *Author:XingHai.Zhao
 *Purpose:Lifecycle实体类
 */
public class LifecycleChecker implements LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    private void onAppForeground() {
        // 应用进入前台
       
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    private void onAppBackground() {
        // 应用进入后台

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private void onAppDESTROY() {
        // 应用销毁

    }

}

更多的生命周期只需要新创建任意名称的方法,加上该注解:@OnLifecycleEvent(Lifecycle.Event.xxx)

Lifecycle.Event.xxx 对应如下类型:

    @SuppressWarnings("WeakerAccess")
    public enum Event {
        /**
         * Constant for onCreate event of the {@link LifecycleOwner}.
         */
        ON_CREATE,
        /**
         * Constant for onStart event of the {@link LifecycleOwner}.
         */
        ON_START,
        /**
         * Constant for onResume event of the {@link LifecycleOwner}.
         */
        ON_RESUME,
        /**
         * Constant for onPause event of the {@link LifecycleOwner}.
         */
        ON_PAUSE,
        /**
         * Constant for onStop event of the {@link LifecycleOwner}.
         */
        ON_STOP,
        /**
         * Constant for onDestroy event of the {@link LifecycleOwner}.
         */
        ON_DESTROY,
        /**
         * An {@link Event Event} constant that can be used to match all events.
         */
        ON_ANY
    }

猜你喜欢

转载自blog.csdn.net/qq_39731011/article/details/119889011
今日推荐