Android Jetpack component (1) LifeCycle

Android Jetpack component series articles:
Android Jetpack component (1) LifeCycle
Android Jetpack component (2) Navigation
Android Jetpack component (3) ViewModel
Android Jetpack component (4) LiveData
Android Jetpack component (5) Room
Android JetPack component (6) DataBinding
Android Jetpack Components (7) Paging
Android Jetpack Components (8) WorkManager

First language

On March 4, Google released Flutter 2 ! As a major upgrade of Flutter, developers using Flutter 2 can use the same code to publish applications developed with Flutter to five operating systems: iOS, Android, Windows, macOS And Linux; and on the web version running on browsers such as Chrome, Firefo, Safari or Edge, Flutter can even be embedded in Cars, TVs and smart appliances.
As a Flutter developer, I immediately downloaded the Flutter 2.0 sdk and ran my Flutter project on Chrome. The effect was very good, but there were some differences in the code, the web side did not support images and dart's io package, etc. The specific differences can be checked on the Flutter official website . Post a web-side rendering.
Flutter 2

Introduction

At the 2017 Google I/O Conference, Google launched AAC (Android Architecture Components), which includes components specifically designed for architecture such as LiveData, ViewModel, and Room. AAC can also be used as the predecessor of Jetpack. At the 2018 Google I/O Conference, Google launched Jetpack on the basis of AAC.

Jetpack is a suite of multiple libraries that can help developers follow best practices, reduce boilerplate code and write code that can run consistently across various Android versions and devices, allowing developers to concentrate on writing important code.
Jetpack mainly includes the following four aspects, namely architecture (Architecture), interface (UI), behavior (Behavior) and foundation (Foundation).

  • Architecture components can help you design robust, testable and maintainable applications.
  • Foundation components provide cross-domain functions, such as backward compatibility, testing and Kotlin language support.
  • Ul components provide widgets and helpers, making the application not only easy to use, but also pleasant to use.
  • The Behavior component helps apps integrate with standard Android services, such as notifications, permissions, sharing, and assistants.
    The Architecture component is the focus of our attention. The following will start learning about the components. The picture below is when Jetpack was first released. Now Jetpack has more components than those in the picture. See all Android Jetpack libraries for detailed components .

Jetpack

advantage

  1. Follow best practices
    Android Jetpack components are built with the latest design methods, are backward compatible, and can reduce crashes and memory leaks.
  2. Eliminate boilerplate code
    Android Jetpack can manage all kinds of cumbersome Activity(such as background tasks, navigation, and lifecycle management) so that you can focus on building great apps.
  3. Reduce inconsistencies.
    These libraries work in a consistent manner across all Android versions and devices, helping you reduce complexity.

AndroidX overview

The artifacts in the AndroidX namespace include the Android Jetpack library. Like the support library, the libraries in the AndroidX namespace are provided separately from the Android platform and are backward compatible with various Android versions.
If you want to migrate the project to AndroidX, select Refactor—>Migrate to AndroidX in the menu bar of Android Studio. After completion, open the gradle.properties file, you can see these two lines of code:

# 表示是否使用AndroidX
android.useAndroidX=true
# 表示是否将第三方库迁移到AndroidX
android.enableJetifier=true

For the new version of Android Studio, AndroidX is already supported by default, and the above operations are not required.

LifeCycle

We often need to onCreate()initialize the components in the middle of the page onPause(), stop the components in the onDestory()middle, and recycle the components in the middle. Such work is cumbersome and the code is difficult to maintain, and it can also cause memory leaks.
To this end, Google provides LifeCycle as a solution. LifeCycle can help developers resume lifecycle-aware components. By using lifecycle-aware components, you can move the code that depends on the component from the lifecycle method into the component itself, thereby reducing the coupling between modules and the possibility of memory leaks. , Write more streamlined code and easy to maintain.

Principle of LifeCycle

Lifecycle is a class for storing related components (e.g., Activityor Fragmentinformation lifecycle state), and to allow other objects to observe this status.
Lifecycle uses two main enumerations to track the lifecycle state of its associated components:

  • Event (Event)
    from the frame and Lifecycledispatched class life cycle events. These events are mapped to Activityand Fragmentcallback events.
 public enum Event {
    
    

        ON_CREATE,
      
        ON_START,
       
        ON_RESUME,
       
        ON_PAUSE,
       
        ON_STOP,
       
        ON_DESTROY,
        
        ON_ANY
 }
  • State (state)
    The current state of the component tracked by the Lifecycle object.
public enum State {
    
    
      
        DESTROYED,

        INITIALIZED,
        
        CREATED,

        STARTED,

        RESUMED;
//比较此状态是否大于或等于给定状态
public boolean isAtLeast(@NonNull State state) {
    
    
            return compareTo(state) >= 0;
}

All of these can be seen from the source code of the Lifecycle class, as shown in the figure below.
LifeCycle
Jetpack provides us with two classes: LifeCycleOwner(observed) and LifeCycleObserver(observer). Monitor the page life cycle through the observer mode.
We ComponentActivitycan see in the source code that it implements the LifecycleOwnerinterface, and there is only one interface getLifeCycle(). LifeCycle uses this method to implement the observer mode. The source code has already implemented the part of the observer.

 public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        LifecycleOwner,
        ViewModelStoreOwner,
        SavedStateRegistryOwner,
        OnBackPressedDispatcherOwner {
    
    
        
  private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
  
  @NonNull
  @Override
  public Lifecycle getLifecycle() {
    
    
        return mLifecycleRegistry;
  }

We listen Atctivitywhen the life cycle, only to realize that part of the code viewer that allows custom components to achieve LifecycleObserverthe interface can be.

public class MyObserver implements LifecycleObserver {
    
    
	//当Activity执行onResume()时,该自动调用
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void connectListener() {
    
    
        ...
    }

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

In Activity, you only need to use the following code to bind the observer and the observed, and no longer worry Activityabout the impact of life cycle changes on the component.

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

LifecycleService

In addition to Android Activityand Fragmenthas a life cycle, there is an important component Servicefor the convenience of Servicelistening lifecycle, Android provides a LifecycleServiceclass that inherits Serviceand implements the LifecycleOwnerinterface. And Activityand Fragmentsimilar, there are also a getLifecycle()for us to call, as part of the source code.

public class LifecycleService extends Service implements LifecycleOwner {
    
    
    private final ServiceLifecycleDispatcher mDispatcher = new ServiceLifecycleDispatcher(this);
    
    @Override
    @NonNull
    public Lifecycle getLifecycle() {
    
    
        return mDispatcher.getLifecycle();
    }
}

When using LifecycleService, we need to add the following dependencies:

implementation "androidx.lifecycle:lifecycle-service:2.3.0"

The usage Activityis similar to that in the Servicemiddle, bind the observer in the Observermiddle, and realize the binding of the event in the customization . Use it LifecycleServicewell to realize the Servicedecoupling between components and manage the changes brought about by the life cycle internally.

ProcessLifecycleOwner

In addition to components with a life cycle Activity, Fragmentand Service, there are Application. Many times we want to know whether the application is in the foreground or the background, or when the background returns to the foreground to get notifications. To this end, LifeCycle provides a ProcessLifecycleOwnerclass to facilitate us to know the life cycle of the entire application.
When using ProcessLifecycleOwner, we need to add the following dependencies:

implementation "androidx.lifecycle:lifecycle-process:2.3.0"

ProcessLifecycleOwnerThe usage method is similar to that of Activity, Fragmentand Serviceits essence is the observer mode, in Applicationwhich the observer Observeris bound, and the event is bound in the custom .
With this ProcessLifecycleOwner, we can easily obtain the changes in the application life cycle, do some business operations in it, and reduce the coupling of the project code. But it should be noted that:

  1. ProcessLifecyoleownerIt is for the monitoring of the entire application, Activityregardless of the number.
  2. Lifecycle.Event.ON CREATEIt will only be called once, and Lifecycle.Event.ON_DESTROYwill never be called.
  3. When the application back to the foreground from the background, or when the application is first opened, it will in turn call Lifecycle.Event.ON_STARTand Lifecycle.Event.ON_RESUME.
  4. When the application retreated back from the front desk (or the user presses the Home key task menu key), will in turn call Lifecycle.Event.ON PAUSEand Lifecycle.Event.ON_ STOP.

ON_STOP event

If you Lifecyclebelong to AppCompatActivityor Fragment, then call AppCompatActivityor Fragmentthe onSaveInstanceState()time, Lifecyclethe status changes CREATEDand dispatches ON_STOPevents. FragmentActivityYou can see it in the source code.

 markFragmentsCreated();
 mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);

 private void markFragmentsCreated() {
    
    
        boolean reiterate;
        do {
    
    
            reiterate = markState(getSupportFragmentManager(), Lifecycle.State.CREATED);
        } while (reiterate);
    }

 private static boolean markState(FragmentManager manager, Lifecycle.State state) {
    
    
        boolean hadNotMarked = false;
        Collection<Fragment> fragments = manager.getFragments();
        for (Fragment fragment : fragments) {
    
    
            if (fragment == null) {
    
    
                continue;
            }
            if (fragment.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED)) {
    
    
                fragment.mLifecycleRegistry.setCurrentState(state);
                hadNotMarked = true;
            }

            if (fragment.getHost() != null) {
    
    
                FragmentManager childFragmentManager = fragment.getChildFragmentManager();
                hadNotMarked |= markState(childFragmentManager, state);
            }
        }
        return hadNotMarked;
  }

After onSaveInstanceState()saving AppCompatActivitythe state of Fragment or , its interface is regarded as immutable until it is called ON_START. If you try to modify the interface after saving state, is likely to lead to inconsistent application of the navigation state, so the application is running in the state of preservation FragmentTransaction, the FragmentManagerexception is thrown.
AppCompatActivityThe onStop()will onSaveInstanceState()after the call, which would leave a gap, which does not allow the interface state changes, but Lifecyclenot yet moved to the CREATEDstate.
To prevent this problem, beta2 and earlier in the Lifecycleclass will be marked as the state CREATEDdoes not dispatch events, so that, even if not dispatch an event (until the system call onStop()), check the current status of the code will get the actual value.

example

  1. Switch between location updates.
  2. Start and stop video buffering.
  3. Start and stop the network connection.
  4. Pause and resume animation drawable resources.

Guess you like

Origin blog.csdn.net/yang_study_first/article/details/115225751