美文网首页
LifecycleObserver(Activity生命周期相关

LifecycleObserver(Activity生命周期相关

作者: 风雪守候 | 来源:发表于2019-04-15 11:39 被阅读0次

    如果某一个代码逻辑和Activity生命周期相关,但是又不想将逻辑代码写到Activity中,那么就可以使用LifecycleObserver,

    首先实现LifecycleObserver接口并写出自己需要的生命周期相关方法,并通过@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)注解来确定生命周期对应的方法

    public class TestLifecycleObserver implements LifecycleObserver {
        private static final String TAG = TestLifecycleObserver.class.getCanonicalName();
    
        public TestLifecycleObserver() {
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
        public void onCreate(){
            Log.e(TAG, "onCreate: ");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        public void onStart(){
            Log.e(TAG, "onStart: ");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
        public void onResume(){
            Log.e(TAG, "onResume: ");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
        public void onPause(){
            Log.e(TAG, "onPause: ");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        public void onStop(){
            Log.e(TAG, "onStop: ");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        public void onDestroy(){
            Log.e(TAG, "onDestroy: ");
        }
    

    然后在对应的Activity中注册TestLifecycleObserver

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            getLifecycle().addObserver(new TestLifecycleObserver());
        }
    

    注意:Lifecycle.Event中并没有onRestart方法对应的常量

    相关文章

      网友评论

          本文标题:LifecycleObserver(Activity生命周期相关

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