Android Jetpack系列学习(二)——Lifecycles

前言

Lifecycles,使用生命周期感知型组件处理生命周期,就是说我们使用Lifecycles之后可以监听activity或者fragment的生命周期从而调用我们组件相对应的方法。

1、文档是以位置定位监听为例子

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

接口,安卓生命周期观察者,实现这个接口,然后我们通过注解来表明函数在LifeCycleOwner的哪个生命周期的时候执行。

2、LifecycleOwner

接口,安卓生命周期的拥有者,ComponentActivity中已经实现了LifecycleOwner接口。


demo的github地址:TenzMixMaster/tenzlifecycles at master · TenzLiu/TenzMixMaster · GitHub

你可能感兴趣的:(Android Jetpack系列学习(二)——Lifecycles)