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.
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 .
advantage
- Follow best practices
Android Jetpack components are built with the latest design methods, are backward compatible, and can reduce crashes and memory leaks. - Eliminate boilerplate code
Android Jetpack can manage all kinds of cumbersomeActivity
(such as background tasks, navigation, and lifecycle management) so that you can focus on building great apps. - 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., Activity
or Fragment
information 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 andLifecycle
dispatched class life cycle events. These events are mapped toActivity
andFragment
callback 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.
Jetpack provides us with two classes: LifeCycleOwner
(observed) and LifeCycleObserver
(observer). Monitor the page life cycle through the observer mode.
We ComponentActivity
can see in the source code that it implements the LifecycleOwner
interface, 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 Atctivity
when the life cycle, only to realize that part of the code viewer that allows custom components to achieve LifecycleObserver
the 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 Activity
about the impact of life cycle changes on the component.
getLifecycle().addObserver(new MyObserver());
LifecycleService
In addition to Android Activity
and Fragment
has a life cycle, there is an important component Service
for the convenience of Service
listening lifecycle, Android provides a LifecycleService
class that inherits Service
and implements the LifecycleOwner
interface. And Activity
and Fragment
similar, 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 Activity
is similar to that in the Service
middle, bind the observer in the Observer
middle, and realize the binding of the event in the customization . Use it LifecycleService
well to realize the Service
decoupling between components and manage the changes brought about by the life cycle internally.
ProcessLifecycleOwner
In addition to components with a life cycle Activity
, Fragment
and 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 ProcessLifecycleOwner
class 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"
ProcessLifecycleOwner
The usage method is similar to that of Activity
, Fragment
and Service
its essence is the observer mode, in Application
which the observer Observer
is 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:
ProcessLifecyoleowner
It is for the monitoring of the entire application,Activity
regardless of the number.Lifecycle.Event.ON CREATE
It will only be called once, andLifecycle.Event.ON_DESTROY
will never be called.- 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_START
andLifecycle.Event.ON_RESUME
. - 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 PAUSE
andLifecycle.Event.ON_ STOP
.
ON_STOP event
If you Lifecycle
belong to AppCompatActivity
or Fragment
, then call AppCompatActivity
or Fragment
the onSaveInstanceState()
time, Lifecycle
the status changes CREATED
and dispatches ON_STOP
events. FragmentActivity
You 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 AppCompatActivity
the 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 FragmentManager
exception is thrown.
AppCompatActivity
The onStop()
will onSaveInstanceState()
after the call, which would leave a gap, which does not allow the interface state changes, but Lifecycle
not yet moved to the CREATED
state.
To prevent this problem, beta2 and earlier in the Lifecycle
class will be marked as the state CREATED
does 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
- Switch between location updates.
- Start and stop video buffering.
- Start and stop the network connection.
- Pause and resume animation drawable resources.