美文网首页
Android Lifecycle 简单使用

Android Lifecycle 简单使用

作者: yunhen | 来源:发表于2018-10-09 11:22 被阅读90次

    观察者类,观察目标的生命周期

    import android.arch.lifecycle.Lifecycle;
    import android.arch.lifecycle.LifecycleObserver;
    import android.arch.lifecycle.OnLifecycleEvent;
    
    public class MyObserver implements LifecycleObserver {
    
        private MyObserver() {
    
        }
    
        private static MyObserver m;
    
        public static MyObserver instance() {
            synchronized (MyObserver.class) {
                if (null == m) {
                    synchronized (MyObserver.class) {
                        m = new MyObserver();
                    }
                }
            }
    
            return m;
        }
    
        @OnLifecycleEvent( Lifecycle.Event.ON_CREATE )
        public void ON_CREATE() {
            System.out.println("MyObserver:ON_CREATE");
        }
    
        @OnLifecycleEvent( Lifecycle.Event.ON_START )
        public void ON_START() {
            System.out.println("MyObserver:ON_START");
        }
    
        @OnLifecycleEvent( Lifecycle.Event.ON_RESUME )
        public void ON_RESUME() {
            System.out.println("@@@@@@@@MyObserver:ON_RESUME");
        }
    
        @OnLifecycleEvent( Lifecycle.Event.ON_PAUSE )
        public void ON_PAUSE() {
            System.out.println("MyObserver:ON_PAUSE");
        }
    
        @OnLifecycleEvent( Lifecycle.Event.ON_STOP )
        public void ON_STOP() {
            System.out.println("MyObserver:ON_STOP");
        }
    
        @OnLifecycleEvent( Lifecycle.Event.ON_DESTROY )
        public void ON_DESTROY() {
            System.out.println("MyObserver:ON_DESTROY");
        }
    
    
    }
    

    被观察的类,一般是activity或fragment

    //实现 LifecycleOwner接口
    //重写
    LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
        @NonNull
        @Override
        public Lifecycle getLifecycle() {
            return mLifecycleRegistry;
        }
    
    

    手动标记生命周期

    @Override
        public void onStart() {
            super.onStart();
            //标记状态
            mLifecycleRegistry.markState(Lifecycle.State.STARTED);
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            //标记状态
            mLifecycleRegistry.markState(Lifecycle.State.RESUMED);
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            //标记状态
            mLifecycleRegistry.markState(Lifecycle.State.DESTROYED);
        }
    

    相关文章

      网友评论

          本文标题:Android Lifecycle 简单使用

          本文链接:https://www.haomeiwen.com/subject/cpjeaftx.html