In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the relevant knowledge of what the use of Lifecycle in Android is, the content is detailed and easy to understand, the operation is simple and fast, and it has a certain reference value. I believe you will gain something after reading this article of Lifecycle in Android. Let's take a look at it.
A brief introduction to Lifecycle
For the introduction of Lifecycle, let's take the official documentation of Google as a reference.
Lifecycle mainly addresses issues related to the business and the Activity/Fragment lifecycle. For example, we request location in onResume () / onStart () and stop location in onPause () / onStop (). So our general practice is:
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 the above code looks OK, in a real application, there may be many ways to perform different operations depending on the current Activity/Fragment lifecycle. Therefore, a large amount of code may be placed in their lifecycle methods, such as onStart () and onStop (), which makes them difficult to maintain. So Lifecycle came into being!
3. The use of Lifecycle
Lifecycle has released the release version, so some of the default support has been included in support-v7:26.1.0 and higher.
Add dependencies:
Implementation "android.arch.lifecycle:extensions:1.1.1" annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
Usage 1: implement the LifecycleObserver interface, use @ OnLifecycleEvent annotations, and generate code through compile-time annotations:
Public class MyLifecycleObserver implements LifecycleObserver {private static final String TAG = MyLifecycleObserver.class.getSimpleName (); @ OnLifecycleEvent (Lifecycle.Event.ON_CREATE) public void start (LifecycleOwner lifecycleOwner) {Lifecycle.State currentState = lifecycleOwner.getLifecycle (). GetCurrentState (); Log.d (TAG, "start:" + currentState);} @ OnLifecycleEvent (Lifecycle.Event.ON_PAUSE) public void stop (LifecycleOwner lifecycleOwner) {Log.d (TAG, "stop:" + lifecycleOwner.getLifecycle (). GetCurrentState ());}}
Code generated by APT
Mode 2: implement the GenericLifecycleObserver interface and its onStateChanged method:
Public class MyLifecycleObserver implements GenericLifecycleObserver {private static final String TAG = MyLifecycleObserver.class.getSimpleName (); @ Override public void onStateChanged (LifecycleOwner source, Lifecycle.Event event) {Log.d (TAG, event.name ());}}
After the creation is complete, we need to add it:
Public class MainActivity extends AppCompatActivity {@ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); getLifecycle () .addObserver (new MyLifecycleObserver ());}}
Result picture:
Method 1
Method 2
4. Source code analysis
Acquisition of 1.Lifecycle
According to the source code tracking, we can see that Lifecycle is in SupportActivity:
Private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry (this); @ Overridepublic Lifecycle getLifecycle () {return mLifecycleRegistry;}
Here's another important code:
SupportActivity.java
Protected void onCreate (@ Nullable Bundle savedInstanceState) {super.onCreate (savedInstanceState); ReportFragment.injectIfNeededIn (this);}
ReportFragment.java
Public static void injectIfNeededIn (Activity activity) {android.app.FragmentManager manager = activity.getFragmentManager (); if (manager.findFragmentByTag (REPORT_FRAGMENT_TAG) = = null) {manager.beginTransaction (). Add (new ReportFragment (), REPORT_FRAGMENT_TAG). Commit (); manager.executePendingTransactions ();}}
Here, a Fragment is added to the Activity. As for the function, I'll talk about it later.
2.addObserver
For the addObserver method, let's take a simple look at it:
LifecycleRegistry.java
@ Overridepublic void addObserver (@ NonNull LifecycleObserver observer) {State initialState = mState = = DESTROYED? DESTROYED: INITIALIZED; ObserverWithState statefulObserver = new ObserverWithState (observer, initialState); ObserverWithState previous = mObserverMap.putIfAbsent (observer, statefulObserver);. / / A pair of status corrections, where the past states will be distributed. That is, if the state has changed when you add observer, you will also be notified! } / / Observerstatic class ObserverWithState {State mState; GenericLifecycleObserver mLifecycleObserver; ObserverWithState (LifecycleObserver observer, State initialState) {mLifecycleObserver = Lifecycling.getCallback (observer); mState = initialState;} void dispatchEvent (LifecycleOwner owner, Event event) {State newState = getStateAfter (event); mState = min (mState, newState); mLifecycleObserver.onStateChanged (owner, event); mState = newState;}}
We convert the implemented interface to an ObserverWithState object through the decorator (I think so) mode and add that object to the mObserverMap.
In the construction method of ObserverWithState, the LifecycleObserver we passed in is wrapped:
Lifecycling.java
@ NonNullstatic GenericLifecycleObserver getCallback (Object object) {/ / this should be regarded as the third implementation, but FullLifecycleObserver is not public, so we cannot use if (object instanceof FullLifecycleObserver) {return new FullLifecycleObserverAdapter ((FullLifecycleObserver) object);} / our first way if (object instanceof GenericLifecycleObserver) {return (GenericLifecycleObserver) object;} / / final Class klass = object.getClass () generated by annotations / / put the generated MyLifecycleObserver_LifecycleAdapter into Map int type = getObserverConstructorType (klass); if (type = = GENERATED_CALLBACK) {List
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.