当前位置:网站首页>2022. Let me take you from getting started to mastering jetpack architecture components - lifecycle

2022. Let me take you from getting started to mastering jetpack architecture components - lifecycle

2022-07-01 13:47:00 InfoQ

Preface

It's not the headline party ! The author will try to make the article easier to understand and more in-depth , This article also follows the author's continuous learning , Continuous updating , If you have any questions, please put them in the comment area ~

Last updated :2022-06-17

Introduce

Jetpack The official debut of 2018 Year of Google I/O At the conference , Four years have passed , Many new components have been added to the original foundation , Each component provides a standard for developers ,  It can help developers reduce boilerplate code and write code that can be used in various fields  Android  The version is consistent with that in the device   Code , Let developers focus on writing important business code . however , There are a lot of Android After four years, engineers have stayed in : know 、 Read about 、 But it didn't work . There are also many friends who want to study hard Jetpack, But the knowledge points on the Internet are too scattered . The goal of this series of articles is to bring you a complete study Jetpack Components , from the shallower to the deeper .

Common architecture component diagram

null
Source address of this series :
https://github.com/taxze6/Jetpack_learn/tree/main/Jetpack_basic_learn

Now let's enter Jetpack The world of , The first stop is Lifecycle Lifecycle management components !

null

Lifecycle

Official documents :
https://developer.android.google.cn/jetpack/androidx/releases/lifecycle

Recommended reading :
In depth understanding of AAC framework  - Lifecycle Overall mechanism source code

Recommended reading :
Lifecycle, After reading this, I really understand

I Believe , When you first saw Lifecycle when , You will have the following four questions :

  • Lifecycle What is it ?
  • What is it used for ?
  • What are its advantages ?
  • How to use it ?

Lifecycle What is it? :

  • life: life ,( Something ) The lifetime of
  • cycle: cycle

Lifecycle Life cycle means . It is a lifecycle aware component , Used to sense and respond to other components , For example, perception Activity and Fragment Changes in the life cycle state of .

Lifecycle What to do :

 Lifecycle Be able to automatically sense the life cycle of other components , It can reduce the coupling between components .

stay android In development , The word life cycle is very important , Because memory leaks have a lot to do with it , The main reason for memory leakage is that the memory of the object cannot be recycled , When a short lifecycle object is referenced by a long lifecycle object , Short lifecycle objects cannot be recycled when they are not in use ….. Under the circumstances , This causes a memory leak .( Leave a hole here , Maybe I will write about how to solve memory leaks in the future , Now you can learn from other materials )

At this time, people will think , I want to manage the lifecycle , however android Of activity Isn't it a function with its own life cycle , I just need to modify it , You have to say coupling , That's all Base Class . There are always ways ~  exactly , During normal development , We will encapsulate a BaseActivity, And then let all Activity All inherited from it .BaseActivity It usually overwrites onCreate、onStart 、onResume、onPause、onStop、onDestroy as well as onRestart function , And add log information , It is convenient to observe the various states of each activity . We can think of packaging BaseActivity, Then the authorities will certainly think of , So it came out Lifecycle.

lifecycle What are the advantages ?

since , We encapsulate ourselves BaseActivity You can basically manage the life cycle , So why should the authorities   Introduction Lifecycle This component ?

advantage :

  • Lifecycler It realizes the separation of execution logic and activities , Code decouples and increases the readability of the code
  • Lifecycler Remove the listener at the end of the activity , Avoid the problem of declaration cycle

How to use Lifecycle Well ?

Let's first get to know lifecycle The core of the class :

  • Lifecycle
  • Lifecycle Is an abstract class , The implementation subclass is LifecycleRegistry

 class LifecycleRegistry extends Lifecycle{
 .......
 }

  • lifecycleRegister
  • lifecycle The only subclass of , Subscription callback logic used to trigger its own state and related observers when the life cycle changes
  • LifecycleOwner
  • Used to connect objects with a lifecycle

 public interface LifecycleOwner {
 @NonNull
 Lifecycle getLifecycle();
 }

  • LifecycleObserver
  • Lifecycle The observer
  • State(Lifecycle Inside the abstract class of )
  • Indicates the current lifecycle state

 public enum State {
 DESTROYED,
 INITIALIZED,
 CREATED,
 STARTED,
 RESUMED;
 public boolean isAtLeast(@NonNull State state) {
 return compareTo(state) >= 0;
 }
 }

  • Event(Lifecycle Inside the abstract class of )
  • The current life cycle changes the corresponding events

 public enum Event {
 ON_CREATE,
 ON_START,
 ON_RESUME,
 ON_PAUSE,
 ON_STOP,
 ON_DESTROY,
 ON_ANY;
 ......
 }

After understanding the use of these classes and interfaces , It will be much easier to learn how to use and analyze the source code .

Lifecycle Use :

  • gradle References to

 dependencies {
 def lifecycle_version = "2.5.0-rc01"
 def arch_version = "2.1.0"
 kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
 implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
 implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"
 implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"
 implementation "androidx.lifecycle:lifecycle-reactivestreams-ktx:$lifecycle_version"
 testImplementation "androidx.arch.core:core-testing:$arch_version"
 }

>   Here we can find that we have imported lifecycle-service,lifecycle-process These two components , because , In the new edition of SDK in ,Activity/Fragment It has been implemented by default LifecycleOwner Interface , in the light of Service,Android  Provided separately LifeCycleService, Not like it Activity、Fragment By default LifeCycleOwner. in the light of Application,Android  Provides ProcessLifeCycleOwner  For listening to the entire application lifecycle .

Now let's do this in two ways Activity Life cycle monitoring

  • LifecycleObserver

We need to create one MyLifecycleTest And inherited from LifecycleObserver , Use OnLifecycleEvent( This method is out of date ), Realize the monitoring of the life cycle .

import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent

//OnLifecycleEvent It's out of date
class MyLifecycleTest : LifecycleObserver {
 companion object{
 private const val TAG = "MyLifecycleTest"
 }
 @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
 fun create() {
 Log.d(TAG, "create: ")
 }

 @OnLifecycleEvent(Lifecycle.Event.ON_START)
 fun start() {
 Log.d(TAG, "start: ")
 }

 @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
 fun resume() {
 Log.d(TAG, "resume: ")
 }

 @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
 fun pause() {
 Log.d(TAG, "pause: ")
 }

 @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
 fun stop() {
 Log.d(TAG, "stop: ")
 }

 @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
 fun destroy() {
 Log.d(TAG, "destroy: ")
 }

 @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
 fun any() {
// Log.d(TAG, "any: ")
 }

}

stay MainActivity onCreate Calls addObserver Method to add a new LifecycleObserver.

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {
 override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)
 setContentView(R.layout.activity_main)
 lifecycle.addObserver(MyLifecycleTest())
 }
}

null
  • Use
    DefaultLifecycleObserver

Using it requires mapping androidx.lifecycle:lifecycle-common-java8, If... Is used in the project java8 Or open java8 characteristic , So the official recommendation is
DefaultLifecycleObserver
Alternative
@OnLifecycleEvent
  Annotation implementation ( Because now annotations have been discarded ), Including precompiling .

We create a
MyDefaultLifecycleObserver Inherited from DefaultLifecycleObserver

import android.util.Log
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner

class MyDefaultLifecycleObserver : DefaultLifecycleObserver {
 companion object {
 private const val TAG = "MyDefaultLifecycleObserver"
 }

 override fun onCreate(owner: LifecycleOwner) {
 super.onCreate(owner)
 Log.d(TAG, "onCreate: ")
 }

 override fun onStart(owner: LifecycleOwner) {
 super.onStart(owner)
 Log.d(TAG, "onStart: ")
 }

 override fun onResume(owner: LifecycleOwner) {
 super.onResume(owner)
 Log.d(TAG, "onResume: ")
 }

 override fun onPause(owner: LifecycleOwner) {
 super.onPause(owner)
 Log.d(TAG, "onPause: ")
 }

 override fun onStop(owner: LifecycleOwner) {
 super.onStop(owner)
 Log.d(TAG, "onStop: ")
 }

 override fun onDestroy(owner: LifecycleOwner) {
 super.onDestroy(owner)
 Log.d(TAG, "onDestroy: ")
 }
}

And then we create another
MyApplication

adopt
addObserver()
take
Observer
Add to
LifecycleRegistry
.

Use ProcessLifecycleOwner.get().lifecycle.addObserver(MyDefaultLifecycleObserver())

import android.app.Application
import androidx.lifecycle.ProcessLifecycleOwner

class MyApplication : Application() {
 override fun onCreate() {
 super.onCreate()
 ProcessLifecycleOwner.get().lifecycle.addObserver(MyDefaultLifecycleObserver())
 }
}

stay AndroidManifest.xml Add the following line of running code to the , When the application process starts , This specified subclass is instantiated before any applied component .

null
null
It's easy to use , Of course , This is just a simple example , So we need to explore Lifecycle The concrete realization of , And practice more to master it .

Several examples Lifecycle Usage scenarios of :

  • Retrofit coordination Lifecycle management Http Life cycle
  • Reading is recommended here :
    https://mp.weixin.qq.com/s/omCnmMX3XVq-vnKoDnQXTg
  • Pause and resume animation
  • Pause and play of video
  • Handler  Remove messages from
  • ........

Here are a few questions :

  • Lifecycle There are several ways to create ( What's the difference , Which one is recommended )?
  • Lifecycle How to synchronize the lifecycle ?
  • Event Events and State What is the relationship between the State ?
  • Lifecycle Registration of , distributed , What is the process of perception ?
  • What is a nested event ? When did it happen ?Lifecycle How to solve it ?

Please find out for yourself , stay Jetpack In the source code analysis series, we will analyze in detail ( This series has not been written yet ).

Foundation Series :

2022 ·  Let me show you Jetpack Architecture components go from beginner to proficient  — Lifecycle ( this paper )

2022 ·  Let me show you Jetpack Architecture components go from beginner to proficient  — ViewModel&LiveData

The following parts are still codewords , Hurry to order a collection

2022 ·  Let me show you Jetpack Architecture components go from beginner to proficient  — DataBinding

2022 ·  Let me show you Jetpack Architecture components go from beginner to proficient  — Navigation

2022 ·  Let me show you Jetpack Architecture components go from beginner to proficient  — Room

2022 ·  Let me show you Jetpack Architecture components go from beginner to proficient  — Paging3

2022 ·  Let me show you Jetpack Architecture components go from beginner to proficient  — WorkManager

2022 ·  Let me show you Jetpack Architecture components go from beginner to proficient  — ViewPager2

2022 ·  Let me show you Jetpack Architecture components go from beginner to proficient  —  Login to the registration page (MVVM)

Advanced Series :

coroutines  + Retrofit Network request status encapsulation

Room  Cache encapsulation

.....
原网站

版权声明
本文为[InfoQ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207011318188923.html