Lifecycle: official introduction
Lifecycle is a class that holds the information about the lifecycle state of a component (like an activity or a fragment) and allows other objects to observe this state.
Lifecycle uses two main enumerations to track the lifecycle status for its associated component.
It means:
Lifecycle it holds information about the lifecycle state of a component, such as Activity and Fragment, and allows other objects to observe the state.
Lifecycles use enumerations to track the lifecycle State of their related components. Look at the source code: (a record State, a record Event).
public static enum State { DESTROYED, INITIALIZED, CREATED, STARTED, RESUMED; private State() { } public boolean isAtLeast(@NonNull Lifecycle.State state) { return this.compareTo(state) >= 0; } } public static enum Event { ON_CREATE, ON_START, ON_RESUME, ON_PAUSE, ON_STOP, ON_DESTROY, ON_ANY; private Event() { } }
Learn to control the life cycle of an Activity through an example, and complete events in each life cycle:
First, define an interface to inherit lifecycle observer, and implement this interface in Activity:
public interface LifecycleHelper extends LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_START) void onStartLifecycle(); @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) void onCreateLifecycle(); @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) void onResumeLifecycle(); @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) void onPauseLifecycle(); @OnLifecycleEvent(Lifecycle.Event.ON_STOP) void onStopLifecycle(); @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) void onDestoryLifecycle(); }
To subscribe in onCreate():
getLifecycle().addObserver(this);
Unsubscribe at ondestore():
getLifecycle().removeObserver(this);
As follows:
public class TeastActivity extends AppCompatActivity implements LifecycleHelper { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_teast); getLifecycle().addObserver(this); } @Override protected void onDestroy() { super.onDestroy(); getLifecycle().removeObserver(this); } @Override public void onStartLifecycle() { } @Override public void onCreateLifecycle() { } @Override public void onResumeLifecycle() { } @Override public void onPauseLifecycle() { } @Override public void onStopLifecycle() { } @Override public void onDestoryLifecycle() { } }