How to use Lifecycle components

2017/5/18 Google IO
Android Architecture Components: a new collection of libraries that can easily manage the UI component life cycle and handle data persistence. Help you design robust, testable, and maintainable applications.
In the following, the life cycle of components such as Fragment and Activity directly uses the word "life cycle", while the life cycle provided by the lifecycle framework is called "life cycle"
In my opinion, the simple understanding of lifecycle is that in a component or tool class, events are automatically accepted to handle the logic of "lifecycle". Decouple component and activity.

Add google Maven warehouse to build.gradle of the project

maven { url "" }

Add the following reference to build.gradle of the module:

implementation "android.arch.lifecycle:runtime:1.0.3"
annotationProcessor "android.arch.lifecycle:compiler:1.0.0"

To implement your own component class, you need to implement LifecycleObserver. The following is just a demonstration class.

public class MyObserver implements LifecycleObserver {
    public void ON_CREATE() {
    public void ON_START() {
    public void ON_RESUME() {
    public void ON_PAUSE() {
    public void ON_STOP() {
    public void ON_DESTROY() {

Then add a statement to your activity and add listening. It is important to note that the addObserver method must be invoked in the onCreate method.

MyObserver myObserver;
protected void onCreate(Bundle savedInstanceState) {
    myObserver = new MyObserver();

Advanced usage:
Lifecycle can be passed in when MyObserver is initialized, and the host's lifecycle status can be confirmed again when MyObserver is operating. For example, if the host is Fragment, if its Activity is in Saved state, calling callback at this time may cause crash.

if (lifecycle.getCurrentState().isAtLeast(STARTED)) {
   //do something

Keywords: Google Android Maven Fragment

Added by nodi on Sun, 03 May 2020 09:45:43 +0300