Why do we need to manage the Activity and Fragment lifecycle? Doesn’t the Framework take care of that for us automatically? OnCreate ->onSart()->onResume()->onPause()->onStop()->onDestory() Is there anything more profound?

digression

In the article on The Data Bing Library, most students reported that it was not necessary for actual development. Because I haven’t loved deeply, I can’t justify it. Just over the weekend to guo Lin public number a talk about the practice of Data Bing in RecyclerView, speak very well, we are free to move forward to read. Practice makes perfect, love deep enough, can rub sparks.

If you have a unique insight or perspective on the Data Binding Library, go to the Data Binding Library and discuss it

Abount Lifecycle-Aware Components

This component responds to state changes in life-cycle components such as activities, fragments, and so on with lightweight and maintainable code.

Eat chestnuts to see what it means:

// Define a listener class that can be used when the Activity lifecycle changes. Class MyLocationListener {public MyLocationListener(Context Context, Callback Callback) {//... } voidstart() {
        // connect to system location service
    }

    void stop() {// disconnect from system location service}} // Call back to listen to the compatactivity related method class MyActivity extends AppActivity { private MyLocationListener myLocationListener; @Override public void onCreate(...) { myLocationListener = new MyLocationListener(this, (location) -> { // update UI }); } @Override public voidonStart() {
        super.onStart();
        myLocationListener.start();
        // manage other components that need to respond
        // to the activity lifecycle
    }

    @Override
    public void onStop() {
        super.onStop();
        myLocationListener.stop();
        // manage other components that need to respond
        // to the activity lifecycle
    }
}
Copy the code

After all, the hand is short, the mouth is soft, and the chestnuts have to be analyzed.

This is pretty simple, just calling the two callback methods of MyLocationListener, but in real life development, most of the time you do a lot of business logic processing and UI updates in the Activity’s onCreate(), onStart(), and so on lifecycle. And if more than one listener class needs to be called back, that means managing the life cycle or callbacks of multiple other components in the Activity. The maintainability and readability of the code is very poor. (Also, a race condition can cause the Activity’s onStop() method to occur before the onStart() method.)

To address this pain point, the package Android.arch. lifecycle provides classes and interfaces to independently manage the lifecycle of Activity and Fragment components.

Lifecycle

A life cycle is a class that contains information about a component’s life cycle state (such as activities and fragments) and allows other objects to observe that state. Lifecycle objects track the Lifecycle state of its associated components in two main enumerated types:

  • The Event Framework and Lifecycle class distribute Lifecycle events and map them to callback events for activities or fragments.
  • The State Lifecycle object tracks the current State of the component.

INITALZIED
DESTROYED
ON_CREATE
ON_START
ON_CREATE

Listen to the lifecycle of a component by adding annotations to a class’s methods. The class is then added as an observer to the class with a life cycle.

Public class MyObserver implements LifecycleObserver {//MyObserver implements LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public voidconnectListener() {... } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) public voiddisconnectListener() {... }} / / myLifecycleOwner class is an implementation of a LifecycleOwner interface, continue to see below myLifecycleOwner... getLifecycle (). The addObserver (new MyObserver ());Copy the code

LifecycleOwner

LifecycleOwner, is an interface that has only one getLifecycle() method, and the class that implements that interface represents a lifecycle. If you want to manage the entire application lifecycle, use ProcessLifecycleOwner instead of LifecycleOwner. The LifecycleOwner interface abstracts the lifecycle ownership of all classes that have a lifecycle to make it easy to read and write during their lifecycle. Classes that implement the LifecycleObserver interface can register with classes that implement LifecycleOwner to observe the lifecycle of the corresponding component. Such as above:

myLifecycleOwner.getLifecycle().addObserver(new MyObserver());
Copy the code

What are the benefits of this? This observer mode allows you to separate logic based on Activity or Fragment lifecycle states into separate classes for better logic development, functional iteration, and post-maintenance.

class MyActivity extends AppCompatActivity {
    private MyLocationListener myLocationListener;

    public void onCreate(...) {
        myLocationListener = new MyLocationListener(this, getLifecycle(), location -> {
            // update UI
        });
        Util.checkUserStatus(result -> {
            if(result) { myLocationListener.enable(); }}); }}Copy the code

At this point you basically know how to use Lifecycle-Aware Components to manage the Lifecycle of an Activity or Fragment. If the LifecycleObserver needs to listen for the life cycle of another Activity or Fragment, it simply needs to reinitialize and register with the new Activity or Fragment. Resources are set up and cleared for recycling without us worrying.

Custom LifecycleOwner

LifecycleOwner is already implemented by default for activities and fragments in Support Library 26.1.0 and later. If you want to implement a custom LifecycleOwner, you need to create a New LifecycleRegistry object and pass related events to it.

public class MyActivity extends Activity implements LifecycleOwner {
    private LifecycleRegistry lifecycleRegistry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        lifecycleRegistry = new LifecycleRegistry(this);
        lifecycleRegistry.markState(Lifecycle.State.CREATED);
    }

    @Override
    public void onStart() {
        super.onStart();
        lifecycleRegistry.markState(Lifecycle.State.STARTED);
    }

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        returnlifecycleRegistry; }}Copy the code

The best practice

  • Keep the UI (Activity or Fragment) simple. Don’t fetch application data in an Activity or Fragment. Use ViewModel or Livedata. That’s why there are MVP, MVVM modes.
  • Try writing a data-driven UI. The UI controller updates the UI or notifies the user when the data changes.
  • Put the processing logic of the data intoViewModelIn the class.ViewModelAs a bridge between UI and data, processing the logic of data and UI interface interaction. Note that it is not logic to fetch data, such as network data or database data.
  • Use the Data Binding Library for maintenance between the UI interface and the UI controller. This helps reduce the amount of code needed to update the UI in an Activity or Fragment. It can be used in JavaButter KnifeLibrary.
  • If the UI is complex, create a Presenter class to handle the view. The MVP pattern?
  • Manage time-consuming tasks using the Kotlin collaboration mechanism.

Scenarios using Lifecycle – Aware Components

Lifecycle – Aware components make it easier to manage the lifecycle of the Acitivity and Fragment in different situations. When is it appropriate to use this component?

  • Switching between coarse and fine granularity. In positioning, for example, if the current interface is visible, the positioning accuracy should be finer and positioning requests more frequently to improve responsiveness. When switching to the background, the frequency of location requests slows down to reduce power consumption
  • Start and stop video buffering. This is the master, buffering the video as early as the application loads, reducing the user’s wait time before the application exits and terminating the buffering.
  • Start and stop network connections. Automatically switch the connection state according to App state.
  • Start and stop drawing pictures. The application does not draw in the background and returns to the foreground to continue drawing.

There are some problems

While fragments or appactivities save state by calling onSaveInstanceState(), their views won’t change until the ON_START event is called, during which time UI changes can cause inconsistencies. This is why the FragmentManager throws an exception when it runs FragmentTransaction after the state is saved.

So if the onStop() method of AppCompatActivity calls the onSaveInstanceState() method, there will be a gap where UI state changes are not allowed, but the lifecycle has not yet changed to an CREATED state. Lifecycle does this by marking the state as CREATED, but does not distribute the event until the onStop() method is called, at which point the true value can be obtained by detecting the current state. But there are still two problems:

  • On Android 6.0 and lower, the system calls the onSaveInstanceState() method, but it doesn’t necessarily call the onStop() method. This will result in events not being distributed, potentially leading observers to believe that Lifecycle is active even though it is stopped.
  • Any class that wants to expose similar behavior in LiveData must implement the methods provided by Lifecycle release Beta 2 and earlier.

Please refer to the official website for more information

conclusion

This article is the understanding or translation of the knowledge on the official website. It is suggested to read the original text further. After all, the original text is original and has many knowledge points. From the first time to see the official website ignorant, to begin to understand, and master a knowledge point. Lifecycle-Aware Components will not only be covered, but also best practices for developing applications in general.

Welcom to visit my github

This is the second article in the Jetpack series

Jetpack: Are you still in findViewById?

Jetpack: How to gracefully update Views as data Changes