Android-Lifecycle

Android-Lifecycle

Android小彩虹2021-08-27 3:56:11190A+A-
  • 有志的人战天斗地,无志的人怨天恨地。

Lifecycle

Lifecycle组建的应用可响应(如 Activity 和 Fragment)的生命周期状态变化。这些组件有助于您写出更有条理且往往更精简的代码,这样的代码更易于维护。

一、UML

Support Library 26.1.0 及更高版本中的 Fragment 和 Activity 已实现 LifecycleOwner 接口

二、相关的接口和涉及到的类

熟悉相关接口和类很有必要。我们一步步来

1.LifecycleOwner

A class that has an Android lifecycle. These events can be used by custom components to handle lifecycle changes without implementing any code inside the Activity or the Fragment.

LifecycleOwner具有Android生命周期的类。可通过LifecycleOwner定制组件,可以使用它所提供的这些事件来处理生命周期更改,而无需在Activity或Fragment中实现任何代码【至于具体实现后面我们会讲到】。源码:

public interface LifecycleOwner {
    Lifecycle getLifecycle();
}

如下我们可以在源码中追溯到所有熟悉的组建andriodx.activity.ComponentActivityandroidx.core.app.ComponentActivityandroidx.fragment.app.Fragment都实现了LifecycleOwner,所以在使用Activity和Fragment不用实现。

2.Lifecycle<-LifecycleRegistry

Defines an object that has an Android Lifecycle. {@link androidx.fragment.app.Fragment Fragment}and {@link androidx.fragment.app.FragmentActivity FragmentActivity} classes implement{@link LifecycleOwner} interface which has the {@link LifecycleOwner#getLifecycle()getLifecycle} method to access the Lifecycle. You can also implement {@link LifecycleOwner}in your own classes.

定义了一个具有生命周期的对象,内部定义了生命周期的事件Event和状态枚举State,以及添加移除订阅者LifecycleObserver事件,获取当前生命周期状态getCurrentState等...

LifecycleRegistry继承实现了Lifecycle,且可以处理多个观察者or订阅者。 在LifecycleRegistry里面我们看到了如下代码:

//用来储存订阅者和状态
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> 
mObserverMap =new FastSafeIterableMap<>();

3.LifecycleEventObserver

我们可以看到UML图中,LifecycleEventObserver实现了LifecycleObserver接口,内部提供了onStateChanged函数作为通知调用。而LifecycleEventObserver储存与mObserverMap集合中等待发送通知,根据当前状态订阅监听状态进行状态分发通知订阅者: 在LifecycleRegistry中,通过addObserver(@NonNull LifecycleObserver observer)将注入的订阅者和当前状态储存到集合mObserverMap中等待状态改变之后作为桥梁进行分发给注册者:

    @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

4.State&Event

我们去源码Lifecycle State:Lifecycle对应Activity生命周期的状态标识枚举,从图中可以看到,依次定义了INITIALIZED、DESTROYED、CREATED、STARTED、RESUMED 5种对应状态且每一种状态都对应Activity不同生命周期时期。

    /** * Lifecycle states. You can consider the states as the nodes in a graph and * {@link Event}s as the edges between these nodes. */
    @SuppressWarnings("WeakerAccess")
    public enum State {
        /** *LifecycleOwner的已销毁状态。此事件之后,生命周期状态分发就不再分发任何事件,此 生命周期将不再分派任何事件。例如,此状态在Activityon的Destroy调用之前到达。 * Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch * any more events. For instance, for an {@link android.app.Activity}, this state is reached * <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call. */
        DESTROYED,

        /** *试图中INITIALIZED->CREATED期间的生命周期代表Activity中CREATED之前的。 * Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is * the state when it is constructed but has not received * {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet. */
        INITIALIZED,

        /** * 对应试Activity中 onCreate到onStop之间的生命周期 * Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state * is reached in two cases: * <ul> * <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call; * <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call. * </ul> */
        CREATED,

        /** * 对应Activity的onStart到onPause之间的生命周期 * Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state * is reached in two cases: * <ul> * <li>after {@link android.app.Activity#onStart() onStart} call; * <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call. * </ul> */
        STARTED,

        /** * Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state * is reached after {@link android.app.Activity#onResume() onResume} is called. */
        RESUMED;

        /** * 对应Activity的onResume * Compares if this State is greater or equal to the given {@code state}. * * @param state State to compare with * @return true if this State is greater or equal to the given {@code state} */
        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0;
        }
    }

Event定义了LifecycleOwner自己的生命周期事件的常量。而当生命周期状态变化或主动执行handleLifecycleEvent之后进行事件分发,例如:事件的分发过程如状态事件图中从INITIALIZED—>CREATED就触发了ON_CREATE

public enum Event {
        /** * Constant for onCreate event of the {@link LifecycleOwner}. */
        ON_CREATE,
        /** * Constant for onStart event of the {@link LifecycleOwner}. */
        ON_START,
        /** * Constant for onResume event of the {@link LifecycleOwner}. */
        ON_RESUME,
        /** * Constant for onPause event of the {@link LifecycleOwner}. */
        ON_PAUSE,
        /** * Constant for onStop event of the {@link LifecycleOwner}. */
        ON_STOP,
        /** * Constant for onDestroy event of the {@link LifecycleOwner}. */
        ON_DESTROY,
        /** * An {@link Event Event} constant that can be used to match all events. */
        ON_ANY
    }

当事件分发下来调用LifecycleRegistry的handleLifecycleEvent()进行依次调用最终调用mLifecycleObserver.onStateChanged(owner, event);进行发送通知订阅者,从而订阅者接收到了生命周期状态通知。

//1.Activity或者lifeRegister生命周期事件分发下来入口
  public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event);
        moveToState(next);
    }
//2.跟新当前状态
private void moveToState(State next) {
        if (mState == next) {
            return;
        }
        mState = next;
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            // we will figure out what to do on upper level.
            return;
        }
        mHandlingEvent = true;
        sync();
        mHandlingEvent = false;
    }
//3.根据当前目标`生命周期状态`和`Observer状态`的顺序序列决定向前还是向后遍历分发
private void sync() ..... /** 4.如果当前目标状态值mState的序列 < Observer状态序列值。 **/ if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
               //4.1 需要Observer减小状态值,直到等于当前目标状态值mState
                backwardPass(lifecycleOwner);
            }
        Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
        if (!mNewEventOccurred && newest != nul && mState.compareTo(newest.getValue().mState) > 0) {
               //4.1 需要Observer增大状态值,直到等于当前目标状态值mState
                forwardPass(lifecycleOwner);
           }
       .....
    }
 //4.向前传递事件,对应图中状态图中的DESTROYED->RESUMED 
   private void forwardPass(LifecycleOwner lifecycleOwner) {
        Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
                mObserverMap.iteratorWithAdditions();
        while (ascendingIterator.hasNext() && !mNewEventOccurred) {
            Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                pushParentState(observer.mState);
                observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
                popParentState();
            }
        }
    }
     //4. 向后传递事件,对应图中的RESUMED -> DESTROYED
     减小Observer的状态值,直到状态值等于当前状态值
    private void backwardPass(LifecycleOwner lifecycleOwner) {
          Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
                mObserverMap.descendingIterator();
        //4.1.1 需要通知Observer减小状态值,直到等于当前目标状态值mState
        while (descendingIterator.hasNext() && !mNewEventOccurred) {
            Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                Event event = downEvent(observer.mState);
                pushParentState(getStateAfter(event));
                //5.进行事件分发,我们去ObserverWithState的dispatchEvent()
                observer.dispatchEvent(lifecycleOwner, event);
                popParentState();
            }
        }
    }
    
 //6.通过mLifecycleObserver通知订阅者生命状态
 static class ObserverWithState {
        State mState;
        LifecycleEventObserver mLifecycleObserver;

        ObserverWithState(LifecycleObserver observer, State initialState) {
            mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
            mState = initialState;
        }

        void dispatchEvent(LifecycleOwner owner, Event event) {
            State newState = getStateAfter(event);
            mState = min(mState, newState);
            //7.通知订阅者
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
    }

3.MainActivity进行注册和添加订阅者事件

我们在Activity添加一个LifecycleEventObserver生命周期事件订阅者,进行事件分发之后的接收。然后运行代码。
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.ComponentActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import com.blankj.utilcode.util.ToastUtils
import com.example.module_map.R
import com.example.module_map.databinding.MapActivityBaseMapBinding

class BaseOberAbleMapActivity : ComponentActivity() {
    lateinit var binding:MapActivityBaseMapBinding
    lateinit var registLifecycle:LifecycleRegistry
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding  = DataBindingUtil.setContentView(this, R.layout.map_activity_base_map)
        Log.e("activity", "envent=ON_CREATE")
        lifecycle.addObserver(object : LifecycleEventObserver {
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                ToastUtils.showLong("lifecycle=" + event.name)
                Log.e("lifecycle", "envent=" + event.name)
            }
        })
    }
    override fun onStart() {
        super.onStart()
        Log.e("activity", "envent=ON_START")

    }

    override fun onPause() {
        super.onPause()
        Log.e("activity", "envent=ON_PAUSE")

    }
    override fun onResume() {
        super.onResume()
        Log.e("activity", "envent=ON_RESUME")

    }
    override fun onRestart() {
        super.onRestart()
        Log.e("activity", "envent=ON_RESTART")

    }

    override fun onStop() {
        super.onStop()
        Log.e("activity", "envent=ON_STOP")

    }
    override fun onDestroy() {
        super.onDestroy()
        Log.e("activity", "envent=ON_DESTROY")

    }
}
//运行结果:
/** E/activity: envent=ON_CREATE E/lifecycle: envent=ON_CREATE E/activity: envent=ON_START E/lifecycle: envent=ON_START E/activity: envent=ON_RESUME E/lifecycle: envent=ON_RESUME **/

上面Activity中,虽然没有主动调用handleLifecycleEvent进行事件的分发,打印可以看到订阅监听中自动接收到了通知,接下来我们继续分析为什么生命周期的变动会自动发送通知。 上面分析我们andriodx.activity.ComponentActivity、androidx.core.app.ComponentActivity、androidx.fragment.app.Fragment都实现了LifecycleOwner,我们可以看到内部都初始化创建了LifecycleRegistry且提供了公共可访问方法getLifecycle()

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;
    }
}    

4.Activity生命周期的变动如何自动通知订阅者

我们在MainActivity中并没有主动调用LifeRegister的handleLifecycleEvent或setCurrentState()进行事件通知订阅者。现在MainActivity生命周期变化也会被触发,猜想有地方主动调用过handleLifecycleEvent,那我们往上找,MainActivity继承了ComponentActivity,在ComponentActivity并没有发现进行分发。但是看到onCreate中有ReportFragment.injectIfNeededIn(this)这么一句:

public class ComponentActivity extends androidx.core.app.ComponentActivity implements LifecycleOwner, ViewModelStoreOwner, SavedStateRegistryOwner, OnBackPressedDispatcherOwner {

    static final class NonConfigurationInstances {
        Object custom;
        ViewModelStore viewModelStore;
    }
    private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSavedStateRegistryController.performRestore(savedInstanceState);
        //这里ReportFragment
        ReportFragment.injectIfNeededIn(this);
        if (mContentLayoutId != 0) {
            setContentView(mContentLayoutId);
        }
    }
}

我们继续查看ReportFragment,这里貌似有很多想要的代码,我们可以看到每一个生命周期中都调用了dispatch,AndroidStudio编译器debug走了一下,的却每次进入应用程序都会跑到ReportFragment各个生命周期事件中进行事件分发。

public class ReportFragment extends Fragment {
    private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"
            + ".LifecycleDispatcher.report_fragment_tag";

    public static void injectIfNeededIn(Activity activity) {
        // ProcessLifecycleOwner should always correctly work and some activities may not extend
        // FragmentActivity from support lib, so we use framework fragments for activities
        android.app.FragmentManager manager = activity.getFragmentManager();
        if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
            manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
            // Hopefully, we are the first to make a transaction.
            manager.executePendingTransactions();
        }
    }

    static ReportFragment get(Activity activity) {
        return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
                REPORT_FRAGMENT_TAG);
    }

    private ActivityInitializationListener mProcessListener;

    private void dispatchCreate(ActivityInitializationListener listener) {
        if (listener != null) {
            listener.onCreate();
        }
    }

    private void dispatchStart(ActivityInitializationListener listener) {
        if (listener != null) {
            listener.onStart();
        }
    }

    private void dispatchResume(ActivityInitializationListener listener) {
        if (listener != null) {
            listener.onResume();
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dispatchCreate(mProcessListener);
        dispatch(Lifecycle.Event.ON_CREATE);
    }

    @Override
    public void onStart() {
        super.onStart();
        dispatchStart(mProcessListener);
        dispatch(Lifecycle.Event.ON_START);
    }

    @Override
    public void onResume() {
        super.onResume();
        dispatchResume(mProcessListener);
        dispatch(Lifecycle.Event.ON_RESUME);
    }

    @Override
    public void onPause() {
        super.onPause();
        dispatch(Lifecycle.Event.ON_PAUSE);
    }

    @Override
    public void onStop() {
        super.onStop();
        dispatch(Lifecycle.Event.ON_STOP);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dispatch(Lifecycle.Event.ON_DESTROY);
        // just want to be sure that we won't leak reference to an activity
        mProcessListener = null;
    }

    private void dispatch(Lifecycle.Event event) {
        Activity activity = getActivity();
        if (activity instanceof LifecycleRegistryOwner) {
            ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
            return;
        }

        if (activity instanceof LifecycleOwner) {
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            if (lifecycle instanceof LifecycleRegistry) {
                ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
            }
        }
    }

    void setProcessListener(ActivityInitializationListener processListener) {
        mProcessListener = processListener;
    }

    interface ActivityInitializationListener {
        void onCreate();

        void onStart();

        void onResume();
    }
}

到这里到底是谁通知ReportFragment,我们查看ReportFragment所使用地方除CompoentActivity之外还有LifecycleDispatcher。在LifecycleDispatcher中我们可以看到:

/** * When initialized, it hooks into the Activity callback of the Application and observes * Activities. It is responsible to hook in child-fragments to activities and fragments to report * their lifecycle events. Another responsibility of this class is to mark as stopped all lifecycle * providers related to an activity as soon it is not safe to run a fragment transaction in this * activity. */
class LifecycleDispatcher {

    private static AtomicBoolean sInitialized = new AtomicBoolean(false);

    static void init(Context context) {
        if (sInitialized.getAndSet(true)) {
            return;
        }
        //1.通过注册Activity生命周期回调函数在监听在DispatcherActivityCallback接收进行分发
        ((Application) context.getApplicationContext())
                .registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
    }

    @SuppressWarnings("WeakerAccess")
    @VisibleForTesting
    static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {

        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            //将activity交给ReportFragment进行调度分发到lifeRegister继续向下分发
            ReportFragment.injectIfNeededIn(activity);
        }

        @Override
        public void onActivityStopped(Activity activity) {
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        }
    }

    private LifecycleDispatcher() {
    }
}

同样在ReportFragment我们发现有setProcessListener(ActivityInitializationListener processListener) 注册貌似监视器我们来看看调用者:

/**提供整个应用程序生命周期 * Class that provides lifecycle for the whole application process. * 因此它只会分发一次ON_CREATE事件 *It is useful for use cases where you would like to react on your app coming *to the foreground or *going to the background and you don't need a milliseconds accuracy in *receiving lifecycle events. *当您希望对即将到来的应用程序或即将进入到后台的应用程序做出反应,并且在接收生命周期事件时不 *需要毫秒级的精度时,ProcessLifecycleOwner */
public class ProcessLifecycleOwner implements LifecycleOwner {

  

    private Handler mHandler;
    private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);

    private Runnable mDelayedPauseRunnable = new Runnable() {
        @Override
        public void run() {
            dispatchPauseIfNeeded();
            dispatchStopIfNeeded();
        }
    };

    ActivityInitializationListener mInitializationListener =
            new ActivityInitializationListener() {
                @Override
                public void onCreate() {
                }

                @Override
                public void onStart() {
                    activityStarted();
                }

                @Override
                public void onResume() {
                    activityResumed();
                }
            };

    private static final ProcessLifecycleOwner sInstance = new ProcessLifecycleOwner();

    static void init(Context context) {
        sInstance.attach(context);
    }

    void activityStarted() {
        mStartedCounter++;
        if (mStartedCounter == 1 && mStopSent) {
            mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
            mStopSent = false;
        }
    }

    void activityResumed() {
        mResumedCounter++;
        if (mResumedCounter == 1) {
            if (mPauseSent) {
                mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
                mPauseSent = false;
            } else {
                mHandler.removeCallbacks(mDelayedPauseRunnable);
            }
        }
    }

    void activityPaused() {
        mResumedCounter--;
        if (mResumedCounter == 0) {
            mHandler.postDelayed(mDelayedPauseRunnable, TIMEOUT_MS);
        }
    }

    void activityStopped() {
        mStartedCounter--;
        dispatchStopIfNeeded();
    }

    void dispatchPauseIfNeeded() {
        if (mResumedCounter == 0) {
            mPauseSent = true;
            mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
        }
    }

    void dispatchStopIfNeeded() {
        if (mStartedCounter == 0 && mPauseSent) {
            mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
            mStopSent = true;
        }
    }

    private ProcessLifecycleOwner() {
    }

    void attach(Context context) {
        mHandler = new Handler();
        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
        Application app = (Application) context.getApplicationContext();
        app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
             //将activity交给ReportFragment进行分发 
ReportFragment.get(activity).setProcessListener(mInitializationListener);
            }

            @Override
            public void onActivityPaused(Activity activity) {
                activityPaused();
            }

            @Override
            public void onActivityStopped(Activity activity) {
                activityStopped();
            }
        });
    }

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mRegistry;
    }
}


同样我们在局部可以看到在attah中将activity交给ReportFragment进行分发。和LifecycleDispatcher一样都通过App.registerActivityLifecycleCallbacks来监听当前activity的生命周期变化,然后交付给ReportFragment进行分发。

通过上面的跟踪我们知道了:

  • ProcessLifecycleOwner

    通过注册Activity生命周期回调函数通知给DispatcherActivityCallback接收进行分发。在onActivityCreated里面进行分发给ReportFragment,通过ReportFragment进行调配分发给LifecycleRegister进行向下分发。

  • LifecycleDispatcher同样通过App.registerActivityLifecycleCallbacks来监听当前activity的生命周期变化,然后交付给ReportFragment进行分发。

ProcessLifecycleOwner和LifecycleDispatcher的初始化继续往上走我们会找到:

ProcessLifecycleOwnerInitializer继承ContentProvider这里我们并没有在Application中进行注册,那可以肯定在清单文件中Lifecyle自动注入了

@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class ProcessLifecycleOwnerInitializer extends ContentProvider {
    @Override
    public boolean onCreate() {
        LifecycleDispatcher.init(getContext());
        ProcessLifecycleOwner.init(getContext());
        return true;
    }

我们运行app之后在build下面看看清单文件

到这里我们明白了Lifecycle组建的原理,下面我们来进行单独的管理我们定位工具的事物周期,避免在activity中关联到每个生命周期事件的节点让代码下显得臃肿。

package com.example.module_map.baseoberservable

import android.content.Context
import android.location.Location
import android.location.LocationListener
import android.util.Log
import androidx.lifecycle.*
import com.blankj.utilcode.util.ToastUtils

/** * * ┌─────────────────────────────────────────────────────────────┐ * │┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐│ * ││Esc│!1 │@2 │#3 │$4 │%5 │^6 │&7 │*8 │(9 │)0 │_- │+= │|\ │`~ ││ * │├───┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴───┤│ * ││ Tab │ Q │ W │ E │ R │ T │ Y │ U │ I │ O │ P │{[ │}] │ BS ││ * │├─────┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴─────┤│ * ││ Ctrl │ A │ S │ D │ F │ G │ H │ J │ K │ L │: ;│" '│ Enter ││ * │├──────┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴────┬───┤│ * ││ Shift │ Z │ X │ C │ V │ B │ N │ M │< ,│> .│? /│Shift │Fn ││ * │└─────┬──┴┬──┴──┬┴───┴───┴───┴───┴───┴──┬┴───┴┬──┴┬─────┴───┘│ * │ │Fn │ Alt │ Space │ Alt │Win│ HHKB │ * │ └───┴─────┴───────────────────────┴─────┴───┘ │ * └─────────────────────────────────────────────────────────────┘ * 版权:渤海新能 版权所有 * * @author feiWang * 版本:1.5 * 创建日期:1/13/21 * 描述:BHNE_OSM * E-mail : 1276998208@qq.com * CSDN:https://blog.csdn.net/m0_37667770/article * GitHub:https://github.com/luhenchang */
class MyLifeCycleOwer(var locationClient:LocationClient) : LifecycleObserver{
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun connectListener() {
        //例如进行定位的location重启操作
        locationClient.resumConnnected()
        ToastUtils.showLong("lifecycle=ON_RESUME")

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun disconnectListener() {
        //进行生命周期相关的其他事件的停止定位
        locationClient.stopConnnected()
        ToastUtils.showLong("lifecycle=ON_PAUSE")
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun removeLocation() {
        locationClient.removeConnnected()
        ToastUtils.showLong("lifecycle=ON_PAUSE")
        Log.e("lifecycle", "envent=ON_PAUSE")
    }
}

我们在activity中注入到自己的LifecycleObserver实现类中进行什么周期和定位工具的事件管理,代码上实现了解偶,分离,看起来更加精简。

class BaseOberAbleMapActivity : ComponentActivity() {
    var locationClient: MyLifeCycleOwer.LocationClient = MyLifeCycleOwer.LocationClient()
    override fun onCreate(savedInstanceState: Bundle?) {
    lifecycle.addObserver(MyLifeCycleOwer(locationClient))
 }
}

到此完结。至于不清楚或者有问题的地方希望指出...

点击这里复制本文地址 以上内容由权冠洲的博客整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!

支持Ctrl+Enter提交

联系我们| 本站介绍| 留言建议 | 交换友链 | 域名展示
本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除

权冠洲的博客 © All Rights Reserved.  Copyright quanguanzhou.top All Rights Reserved
苏公网安备 32030302000848号   苏ICP备20033101号-1
本网站由 提供CDN/云存储服务

联系我们