Efficient learning model
What -->why--> How model is? --> Why? --> How to use? --> Realization principle --> Summary and share (Learn to apply)Copy the code
What is Lifecycle?
Lifecylce: Lifecycle-aware components that adjust behavior by sensing the lifecycle state of an Activity/Fragment;Copy the code
Why Lifecycle is used?
Scenario analysis 1: For example, multiple activities need to perform the same logical operation in onStart(),onResume(),onPause(), and onSopt(). In this case, an Activity may omit to write code, which is inevitable, resulting in code consistency problems and requiring unified management. Resolve consistency issues: this can be implemented through interface callbacks, but introduces code intrusion issues; Scenario analysis 2: The code uses a Handler that holds the context object, which needs to be removed in onDestroy(). Otherwise, memory leaks may occur. Lifecycle is introduced to solve the problem of the scenario described above; Lifecycle will help lifecycle as follows: 1. 2. Solve code intrusion problems; 3. Solve the memory leakage problem;Copy the code
Iii. How can Lifecycle be used?
1. Customize the Observer implementation LifecycleObserver interface by adding annotations to methods that require uniform implementation: public class MyObserver implements LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public void connectListener() { ... } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) public void disconnectListener() { ... }} 2. Add a view to your Activity/Fragment: getLifecycle().addobServer (new MyObserver());Copy the code