前言
Lifecycles葛虐,使用生命周期感知型組件處理生命周期,就是說我們使用Lifecycles之后可以監(jiān)聽activity或者fragment的生命周期從而調用我們組件相對應的方法。
1徽千、文檔是以位置定位監(jiān)聽為例子
public class MyLocationListenerimplements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart(){
Log.e("tenz","MyLocationListener:onStart().......");
? ? ? ? //開始獲取位置
? ? }
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate() {
Log.e("tenz","MyLocationListener:onCreate().......");
? ? }
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {
Log.e("tenz","MyLocationListener:onResume().......");
? ? }
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause() {
Log.e("tenz","MyLocationListener:onPause().......");
? ? }
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop() {
Log.e("tenz","MyLocationListener:onStop().......");
? ? ? ? //釋放資源
? ? }
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
Log.e("tenz","MyLocationListener:onDestroy().......");
? ? }
}
public class MainActivityextends AppCompatActivity {
private ActivityMainBindingviewDataBinding;
? ? @Override
? ? protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
? ? ? ? viewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
? ? ? ? getLifecycle().addObserver(new MyLocationListener());
? ? ? ? Log.e("tenz","activity:onCreate()--------");
? ? }
@Override
? ? protected void onStart() {
super.onStart();
? ? ? ? Log.e("tenz","activity:onStart()--------");
? ? }
@Override
? ? protected void onResume() {
super.onResume();
? ? ? ? Log.e("tenz","activity:onResume()--------");
? ? }
@Override
? ? protected void onPause() {
super.onPause();
? ? ? ? Log.e("tenz","activity:onPause()--------");
? ? }
@Override
? ? protected void onRestart() {
super.onRestart();
? ? ? ? Log.e("tenz","activity:onRestart()--------");
? ? }
@Override
? ? protected void onStop() {
super.onStop();
? ? ? ? Log.e("tenz","activity:onStop()--------");
? ? }
@Override
? ? protected void onDestroy() {
super.onDestroy();
? ? ? ? Log.e("tenz","MyLocationListener:onDestroy()--------");
? ? }
}
1、LifecycleObserver
接口,安卓生命周期觀察者楼雹,實現(xiàn)這個接口,然后我們通過注解來表明函數(shù)在LifeCycleOwner的哪個生命周期的時候執(zhí)行。
2烘豹、LifecycleOwner
接口瓜贾,安卓生命周期的擁有者,ComponentActivity中已經(jīng)實現(xiàn)了LifecycleOwner接口携悯。
demo的github地址:TenzMixMaster/tenzlifecycles at master · TenzLiu/TenzMixMaster · GitHub