1.直接增加如下依靠就能够满意日常的工作,假如缺少哪个库,再去单独增加就好了
implementation”android.arch.lifecycle:extensions:1.1.1″
增加这一句代码就依靠了如下的库。
eXj6eJ.png
2.先不谈Activity和Fragment中怎么运用,先举一个Lifecycle的简略比如。
1ackagecom.example.lifecycledemo1;23importandroid.arch.lifecycle.Lifecycle;4importandroid.arch.lifecycle.LifecycleObserver;5importandroid.arch.lifecycle.OnLifecycleEvent;6importandroid.support.v7.app.AppCompatActivity;7importandroid.os.Bundle;8importandroid.util.Log;910publicclassMainActivityextendsAppCompatActivity{1112privatestaticfinalStringTAG=”MainActivity”;1314@Override15protectedvoidonCreate(BundlesavedInstanceState){16super.onCreate(savedInstanceState);17setContentView(R.layout.activity_main);18getLifecycle().addObserver(newMyObserver());//119}2021publicclassMyObserverimplementsLifecycleObserver{2223@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)24voidonResume(){25Log.d(TAG,”LifecyclecallonResume”);26}27@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)28voidonPause(){29Log.d(TAG,”LifecyclecallonPause”);30}31}3233@Override34protectedvoidonResume(){35super.onResume();36Log.d(TAG,”onResume”);37}3839@Override40protectedvoidonPause(){41super.onPause();42Log.d(TAG,”onPause”);4344}45}
先完成MyObserver,对ON_CREATE和ON_RESUME事件进行监听。由于在AndroidSupportLibrary26.1.0及其之后的版本,Activity和Fragment已经默许完成了LifecycleOwner接口,所以在注释1处能够直接运用getLifecycle办法获取Lifecycle对象,这样MyObserver就能够调查MainActivity的生命周期变化了,LifecycleOwner能够理解为被调查者,MainActivity默许完成了LifecycleOwner接口,也就是说MainActivity是被调查者。
运行程序,打印的log如下所示。
D/MainActivity:onResume
D/MainActivity:LifecyclecallonResume
D/MainActivity:LifecyclecallonPause
D/MainActivity:onPause
3.MVP的比如
1publicclassMyPresenterimplementsIPresenter{2privatestaticfinalStringTAG=”test”;34@Override5publicvoidonResume(){6Log.d(TAG,”LifecyclecallonResume”);7}89@Override10publicvoidonPause(){11Log.d(TAG,”LifecyclecallonPause”);12}13}1415interfaceIPresenterextendsLifecycleObserver{1617@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)18voidonResume();1920@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)21voidonPause();22}
IPresenter接口承继自LifecycleObserver接口,MyPresenter又完成了IPresenter接口,这样MyPresenter成为了一个调查者。
接在在MainActivity中加入MyPresenter:
1publicclassMainActivityextendsAppCompatActivity{23privatestaticfinalStringTAG=”test”;4privateIPresentermPresenter;5@Override6protectedvoidonCreate(BundlesavedInstanceState){7super.onCreate(savedInstanceState);8setContentView(R.layout.activity_main);9mPresenter=newMyPresenter();10getLifecycle().addObserver(mPresenter);11}1213@Override14protectedvoidonResume(){15super.onResume();16Log.d(TAG,”onResume”);17}1819@Override20protectedvoidonPause(){21super.onPause();22Log.d(TAG,”onPause”);2324}25}
MainActivity成为了被调查者,当它的生命周期发生变化时,MyPresenter就能够调查到,这样就不需要在MainActivity的多个生命周期办法中调用MyPresenter的办法了。
打印的日志如下:
D/test:onResume
D/test:LifecyclecallonResume
D/test:LifecyclecallonPause
D/test:onPause