Android JetPack architectural components of Lifecycle (six)

Ali P7 mobile Internet architect, Advanced Video (Daily update) for free learning, please click: https://space.bilibili.com/474380680

Life cycle-aware components processing lifecycle

Lifecycle aware components can take action when other components (such as activity and fragment) lifecycle state changes. These components can help us generate more lightweight and easier to maintain code.

We usually achieve their business logic in activity and fragment of the life cycle approach. However, this approach will lead to an increase in bad and error code organization. But through the use of life-cycle-aware components, we can code components will depend on the life cycle out of the life-cycle approach.

Android.arch.lifecycle package provides classes and interfaces, so that we can build lifecycle aware components - These components can automatically adjust its behavior according to the current state of the life cycle of activity and fragment.

Most Android Framework application components are defined in additional life cycle. Lifecycle run by an operating system or in the process of Framework code management. They are the core Android operating principle, our applications must follow them, failure to do so could trigger a memory leak even application crashes.

Suppose we now have an activity, device location to display on the phone screen. Common implementation may be as follows:

class MyLocationListener {
    public MyLocationListener(Context context, Callback callback) {
        // ...
    }

    void start() {
        // connect to system location service
    }

    void stop() {
        // disconnect from system location service
    }
}


class MyActivity extends AppCompatActivity {
    private MyLocationListener myLocationListener;

    @Override
    public void onCreate(...) {
        myLocationListener = new MyLocationListener(this, (location) -> {
            // update UI
        });
    }

    @Override
    public void onStart() {
        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
    }
}

Although this example looks good, but in practical application, the final will be a lot of callbacks to manage the UI and other components in response to the current state of the life cycle. Manage the plurality of components is placed in the life cycle of a large amount of code in the method, such as lead onStart () and onStop () This method is difficult to maintain.

In addition, we can not guarantee MyLocationListener before MyActivity stop-start, if we need to perform long-running operations (for example, some configuration check onStart () in), which can lead to onStop MyActivity of () before the completion of this operation will callback , which makes components to keep their activities take longer time required.

class MyActivity extends AppCompatActivity {
    private MyLocationListener myLocationListener;

    public void onCreate(...) {
        myLocationListener = new MyLocationListener(this, location -> {
            // update UI
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        Util.checkUserStatus(result -> {
            // what if this callback is invoked AFTER activity is stopped?
            if (result) {
                myLocationListener.start();
            }
        });
    }

    @Override
    public void onStop() {
        super.onStop();
        myLocationListener.stop();
    }
}

android.arch.lifecycle package provides classes and interfaces that can help us to isolate and elasticity ways to solve these problems.

Life cycle

Lifecycle is held on a component (e.g., the fragment or activity) and life cycle state information allows other objects of this class observation state.

Lifecycle two main enumeration to track the life cycle state of its associated components:

Event

Distribution and life cycle events from Lifecycle Framework class. These events are mapped to callbacks and event activities in fragments.

State

To keep track of the current state of the object component by Lifecycle.

 

 
19956127-8135ce224007f36a.png
 

 

The State regarded as nodes of the graph, the Event regarded as the edge between the nodes.

A class can monitor its lifecycle state by adding annotations to the method of assembly. We can add a viewer by calling the addObserver () method Lifecycle class, instance and passes a viewer, as shown in the following example:

public class MyObserver implements LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void connectListener() {
        ...
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void disconnectListener() {
        ...
    }
}

myLifecycleOwner.getLifecycle().addObserver(new MyObserver());

In the example above, myLifecycleOwner LifecycleOwner object implements the interface, this will be described in the next section.

LifecycleOwner

LifecycleOwner is an interface, it is only a getLifecycle () method, indicating implement LifecycleOwner class interface has a Lifecycle. If you are trying to manage the entire life cycle of the application process, you can look ProcessLifecycleOwner.

LifecycleOwner the interface from the individual classes (e.g. Fragment and AppCompatActivity) abstracted Lifecycle, ownership, and allow the assembly prepared for use therewith. Any custom class can implement LifecycleOwner interface.

Realized LifecycleObserver components and implementation components LifecycleOwner can seamlessly work, because the owner can provide life-cycle, the viewer can observe the registration.

Examples of location tracking example, we can make MyLocationListener class implements LifecycleObserver, and () method initializes it onCreate activity life cycle, which means that the life cycle in response to the logic state change can not be declared MyLocationListener Activity, when the logical after the code is placed in the respective assembly, and can make activities more manageable fragments.

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();
            }
        });
  }
}

A common use case is, if Lifecycle now not active, you should avoid calling some callback. For example: if a callback is saved in the Activity state to onSaveInstanceState () run Fragment Transaction, it will trigger a crash, so we will avoid calling the callback.

To simplify this use case, Lifecycle classes allow other objects to query the current state.

class MyLocationListener implements LifecycleObserver {
    private boolean enabled = false;
    public MyLocationListener(Context context, Lifecycle lifecycle, Callback callback) {
       ...
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    void start() {
        if (enabled) {
           // connect
        }
    }

    public void enable() {
        enabled = true;
        if (lifecycle.getCurrentState().isAtLeast(STARTED)) {
            // connect if not connected
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    void stop() {
        // disconnect if connected
    }
}

With this realization, we can perceive LocationListener class life cycle. If we need to use LocationListener from another activity or fragment, we only need to initialize it. All settings and unloading operations by LocationListener management class itself.

If you need to use a library provides life-cycle class Android, Google suggested that we use the life-cycle-aware components. Our clients can easily integrate these components without the need to manually manage the life cycle of the client.

Implementing Custom LifecycleOwner

In Support Library 26.1.0 and later Fragments and Activities has been achieved LifecycleOwner interface.

If you want custom classes become LifecycleOwner, you can use LifecycleRegistry class, but you need to forward to the life-cycle events such as the following code:

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

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

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

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

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
}

Lifecycle perceived best practice components

As streamline our UI controls (Activity and Fragment). They should not try to get their data, on the contrary, should do this using the ViewModel, and observe LiveData data subject to change to reflect the view.

Write data-driven UI, UI view controller is responsible for updating the data changes, or to notify the user operates the ViewModel.

The logic of our data on the ViewModel class. ViewModel should as a bridge between the controller and the remainder of the application UI. But ViewModel is not acquiring data (such as from the network) duties. Instead, the ViewModel should invoke the appropriate components (e.g., component Repository) to retrieve the data, then the result is provided to the UI controller.

Data Binding used to maintain a clean interface between the controller and the UI view. This will make our views more declarative, and to minimize the code needed to write an update in the Activity and Fragment. If you prefer to use the Java programming language to do this, then use Butter Knife like the library to avoid boilerplate code, make the code better abstraction.

If your UI is complex, consider creating a presenter class to handle UI changes. This can be a boring task, but it allows us to UI components easier to test.

Avoid referencing context View or Activity in your ViewModel in. If ViewModel survival time than this activity (such as in the case of configuration changes), leading to the garbage collector does not correctly handle activity cause a memory leak.

Lifecycle perceived use of the assembly

Lifecycle aware components allows us to more easily manage the life cycle in a variety of situations. For example, the following scenario:

Switching between coarse-grained and fine-grained location update. Life cycle-aware components to enable fine-grained location update our position in the application is visible when in the background and switch to coarse-grained application update. LiveData is a life-cycle-aware components, which allows our application to automatically update the UI when the user changes location.

Stop and start the video buffer. Life cycle-aware components can open the video buffer as soon as possible, but to postpone play until the application is fully started. We can also use life-cycle-aware components at the time of termination buffer destroyed applications.

Start and stop network connections. Life cycle-aware components to enable real-time updates of the data network (streaming) when the application is in the foreground, and automatically pauses when an application goes into the background.

Pause and resume animators. When an application in the background, using a life-cycle pause drawn animation content-aware components, and application recovery drawn contents in the foreground.

Event processing ON_STOP

If you belong to a AppCompatActivity a Lifecycle or Fragment, when AppCompatActivity or Fragment of onSaveInstanceState () method is called, the state will become Lifecycle CREATED, its ON_STOP event will be distributed.

When the state of one or Fragment AppCompatActivity is saved to onSaveInstanceState (), it is called UI before ON_START are considered immutable. The reason attempt to modify the UI after saving the state could lead to inconsistent navigation status of the application, which is why if the application is running FragmentTransaction after saving state, FragmentManager will throw an exception, detailed reasons please see the commit ().

If the association is not Lifecycle STARTED state observer, LiveData be avoided by calling its edges to prevent this situation the viewer out of the box. Behind, it will ensure that calls isAtLeast before calling its viewers ().

Egg pain is, AppCompatActivity of onStop () method will onSaveInstanceState () after the call, which causes the program to leave the state but is not allowed to change the UI Lifecycle and not into the interval CREATED state.

To prevent this problem, beta2 version of Lifecycle class and lower version CREATED state marked as scheduling events, even if the calling onStop (in the system) before unscheduled event, check the current status of any code that will get the actual value.

Sad reminder that this solution has two major problems:

And the lower-level API 23, Android system actually saved the state of the activity, even though it is partially covered by another activity. In other words, Android system calls onSaveInstanceState () but does not have to call onStop (). This creates a potentially long interval, even if it can not be modified UI state, observers still - - consider the life cycle is active.

Any class you want to expose similar behavior to LiveData class must implement solutions Lifecycle beta 2 version and earlier offer.

note

To make this process easier, and to provide better compatibility with older versions, starting from 1.0.0-rc1 version, when calling onSaveInstanceState () Lifecycle object is marked as CREATED and scheduling ON_STOP, without waiting call onStop () method . This may not affect our code, but we need to pay attention to this because it does not match the order of invocation API 26 and the lower-level Activity class.

Original link: https://blog.csdn.net/guiying712/article/details/81176039
Ali P7 mobile Internet architect, Advanced Video (Daily update) for free learning, please click: https://space.bilibili.com/ 474 380 680

Guess you like

Origin www.cnblogs.com/Android-Alvin/p/12109549.html