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 "https://maven.google.com" }
Add the following reference to build.gradle of the module:
//Lifecycle
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 {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void ON_CREATE() {
System.out.println("@@@@@@@@MyObserver:ON_CREATE");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void ON_START() {
System.out.println("@@@@@@@@MyObserver:ON_START");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void ON_RESUME() {
System.out.println("@@@@@@@@MyObserver:ON_RESUME");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void ON_PAUSE() {
System.out.println("@@@@@@@@MyObserver:ON_PAUSE");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void ON_STOP() {
System.out.println("@@@@@@@@MyObserver:ON_STOP");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void ON_DESTROY() {
System.out.println("@@@@@@@@MyObserver: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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myObserver = new MyObserver();
getLifecycle().addObserver(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
}