Introduction to the Official Android architecture components lifecycle
Here is an architecture diagram of the official Android app development:
From can see some keywords: ViewModel , LiveData , Room et. Actually read the above video will find Google's official Android architecture components include the following:
- LifeCycle: Related to the life cycle of activity and fragment
- Livedata: Asynchronous subscription data, also life-cycle aware
- ViewModel: View data holding model, also life cycle awareness
- Room:sqlite abstraction layer for simplifying sqlite data storage
This article mainly explains the simple usage of lifecycle in the project
Add dependency in AS
First add the content to the project root directory build.gradle :
allprojects { repositories { jcenter () maven {URL ' https://maven.google.com '} //Add this line }}
Then add the following dependencies in the app directory build.gradle :
// for lifecycles, Livedata, and ViewModelcompile "android.arch.lifecycle:runtime:1.0.0-alpha1"" ANDROID.ARCH.LIFECYCLE:EXTENSIONS:1.0.0-ALPHA1 "" ANDROID.ARCH.LIFECYCLE:COMPILER:1.0.0-ALPHA1 "// for Compile "android.arch.persistence.room:runtime:1.0.0-alpha1"" ANDROID.ARCH.PERSISTENCE.ROOM:COMPILER:1.0.0-ALPHA1 "
Lifecycle related uses
In our usual projects, we often encounter many logic processes that need to rely on life cycle, such as having such a requirement.
In an activity we need to show the user's geographic location on the screen. The simple implementation method is as follows:
Lass Mylocationlistener { PublicMylocationlistener (Context context, Callback Callback) {// ... } voidstart () {//Connect to System location Service } voidStop () {//Disconnect from System location service }}classMyActivityextendsappcompatactivity {PrivateMylocationlistener Mylocationlistener; Public voidonCreate (...) {Mylocationlistener=NewMylocationlistener ( This, (location), { //Update UI }); } Public voidOnStart () {Super. OnStart (); Mylocationlistener.start (); } Public voidOnStop () {Super. OnStop (); Mylocationlistener.stop (); }}
Although the above code looks concise, the Onstart,onstop method in the actual project may become quite large.
In addition, the actual situation may not be as simple as above, for example, we need to monitor the start position before the user state detection, detection is a time-consuming task, it is likely that the user before the end of the detection of activity early, this time will cause myLocationListener.start() the call in the myLocationListener.stop() back, This can cause many problems that are difficult to locate. The code is as follows:
classMyActivityextendsappcompatactivity {PrivateMylocationlistener Mylocationlistener; Public voidonCreate (...) {Mylocationlistener=NewMylocationlistener ( This, Location- { //Update UI }); } Public voidOnStart () {Super. OnStart (); Util.checkuserstatus (Result- { //What if the callback is invoked after activity is stopped? if(Result) {Mylocationlistener.start (); } }); } Public voidOnStop () {Super. OnStop (); Mylocationlistener.stop (); }}
This is the time for today's protagonist LifeCycle . It provides a set of interfaces to help you deal with these problems.
LifeCycle
LifeCyleClass holds information about the life cycle of activity or fragment, and enables other objects to listen to these states.
LifeCyleThere are two enumerations used to track the state in the life cycle.
Event
This is the life cycle event class, which is passed between the framework and the lifecycle, and these events are mapped to activity and fragment callback events.
State
The current state of activity or fragment held by lifecycle.
A class wants to listen to the state of the lifecycle, just add annotations to its methods:
Public class Implements lifecycleobserver { @OnLifecycleEvent (Lifecycle.Event.ON_RESUME) publicvoid Onresume () { } @OnLifecycleEvent (Lifecycle.Event.ON_PAUSE) publicvoid OnPause () { }}alifecycleowner.getlifecycle (). Addobserver(new myobserver ());
Lifecycleowner
LifeCycleOwneris an interface that has only one method to indicate that it has a lifecycle object. This method is for getLifecycle() .
This object provides a good abstraction for acitivity,fragment and lifecycle, and the activity and fragment can be used to implement lifecycle monitoring with lifecycle as long as the interface is implemented.
Note: Since lifecycle is currently in the alpha phase, fragment and appcompatactivity do not implement these methods, and before that can be used LifecycleActivity LifecycleFragment . After the lifecycle stabilizes, fragment and appcompatactivity will implement these by default.
For the previous position listener example, we can let MyLocationListener inherit lifecycleobserver, use lifecycle in the OnCreate to initialize, the remaining problems do not have to worry about. Because they MyLocationListener have the ability to make life-cycle judgments.
classMyActivityextendslifecycleactivity {PrivateMylocationlistener Mylocationlistener; Public voidonCreate (...) { //Initialize the getlifecycle () Incoming lifecycle object hereMylocationlistener =NewMylocationlistener ( This, Getlifecycle (), Location- { //Update UI }); //detect user status and enable monitoringUtil.checkuserstatus (Result- { if(Result) {mylocationlistener.enable (); } }); }}
Here's a look at Mylocationlistener.
classMylocationlistenerImplementsLifecycleobserver {Private BooleanEnabled =false; PublicMylocationlistener (Context context, Lifecycle Lifecycle, Callback Callback) {...} @OnLifecycleEvent (Lifecycle.Event.ON_START)voidstart () {if(enabled) {//Connect } } Public voidenable () {enabled=true; //? if(Lifecycle.getstate (). Isatleast (STARTED)) {//Connect if not connected}} @OnLifecycleEvent (Lifecycle.Event.ON_STOP)voidStop () {//Disconnect if connected }}
The most important feature of lifecycle is that he can provide a way to proactively query the life cycle state. This avoids the problem that is myLocationListener.start() called later in the previous meeting myLocationListener.stop() .
Through this implementation, we LocationListener are fully aware of life cycle, it can do its own initialization and resource cleanup without being subject to activity or fragment management. At this point if we use it in other activity or fragment LocationListener , we just need to initialize it so we don't have to worry about the life cycle effect on it, because it will do it internally.
The class that works through Lefecycle is what we call it 生命周期感知 . Libraries that require classes that use the Android life cycle are encouraged to provide lifecycle-aware components so that clients can easily integrate these classes on the client without manual lifecycle management.
LiveDatais an example of a lifecycle-aware component that uses livedata and ViewModel to make it easier to populate the UI with data that follows the Android lifecycle.
Best Practices for life cycle
- Keep your UI (activity and fragment) as concise as possible. Instead of trying to get their data, they should use ViewModel to do this and update the data into the UI through Livedata callbacks.
- Trying to write a data-driven UI, the responsibility of your UI is to update the view when the data changes, or to notify ViewModel of the user action.
- Put your data logic in the ViewModel class. ViewModel should be used as a connector for UI and other data manipulation. It is important to note that ViewModel is not responsible for extracting data (for example, from the network). Instead, ViewModel should call other interfaces to do this work, and then provide the results to the UI.
- Use
Data Binding can make your UI code quite neat. This will make your UI more declarative and minimize the code to write UI updates. If you prefer to do this in Java, use Butter Knife a library like this to avoid using boilerplate code and make better abstractions.
- If you have a complex UI, consider creating a presenter class to handle UI modifications. This is often over-architected, but may help make your UI easier to test.
- Do not refer to the view or activity context in ViewModel. If the ViewModel is still alive in the event of activity or view destruction, a memory leak will occur.
Add
This interface can be implemented by implementing Lifecycleowner in a custom activity or fragment LifecycleRegistryOwner . Rather than inheritance (Lifecyclefragment and Lifecycleactivity)
Public class extends Implements Lifecycleregistryowner { new lifecycleregistry (this); @Override public lifecycleregistry getlifecycle () { return lifecycleregistry;} }
If you want to implement Lifecycleowner in a custom class, you can use it LifecycleRegistry , but you need to proactively forward events to it for the life cycle. But if your custom classes are fragment and activity, and they implement Lifecycleregistryowner, then event forwarding is done automatically.
Android Official architecture Components introduction of Lifecycle (i)