Android中的Lifecycle有什么用-创新互联
这篇文章主要介绍了Android中的Lifecycle有什么用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Android中的Lifecycle有什么用文章都会有所收获,下面我们一起来看看吧。
成都创新互联是一家专注于网站设计制作、做网站与策划设计,船营网站建设哪家好?成都创新互联做网站,专注于网站建设10余年,网设计领域的专业建站公司;建站业务涵盖:船营等地区。船营做网站价格咨询:18982081108Lifecycle的简单介绍
Lifecycle的介绍,我们还是拿Google的官方文档作为参考吧。
Lifecycle主要解决的是业务和Activity/Fragment生命周期相关的问题。例如:我们在onResume()/onStart()中请求定位,在onPause()/onStop()中停止定位。那么我们一般的做法:
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 } }
上面的代码虽然看起来还可以,但在真实的应用程序中,可能会有很多的方法都需要根据当前Activity/Fragment的生命周期来进行不同的操作。因此其生命周期方法中可能会被放置大量代码,例如onStart()和 onStop()中,这使得它们难以维护。因此Lifecycle应运而生!
3. Lifecycle的使用
Lifecycle已经发布了release版,所以其中的一些默认支持已经包含到了support-v7:26.1.0以及更高。
添加依赖:
implementation "android.arch.lifecycle:extensions:1.1.1" annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
使用方式1:实现LifecycleObserver接口,使用@OnLifecycleEvent注解,通过编译时注解生成代码:
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()); } }
APT生成的代码
使用方式2:实现GenericLifecycleObserver接口,实现其onStateChanged方法:
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()); } }
创建完成后,我们需要将其添加:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getLifecycle().addObserver(new MyLifecycleObserver()); } }
结果图:
方法1
方法2
4. 源码分析
1.Lifecycle的获取
根据源码追踪我们可以看到Lifecycle是在SupportActivity中:
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); @Override public Lifecycle getLifecycle() { return mLifecycleRegistry; }
这里还有个挺重要的代码:
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(); } }
这里在Activity中添加了一个Fragment,至于作用,留到后面在讲。
2.addObserver
addObserver方法的话,还是简单来看吧:
LifecycleRegistry.java
@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); ...... // 对状态的修正,这里会对已经过去的状态进行分发。也就是说如果添加observer时状态已经改变,那么也会被通知到! } // 有状态的Observer static 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; } }
我们将实现的接口通过装饰者(我认为是这样)模式转成ObserverWithState对象,并将该对象添加到mObserverMap中。
在ObserverWithState的构造方法中,有对我们传入的LifecycleObserver进行包装:
Lifecycling.java
@NonNull static GenericLifecycleObserver getCallback(Object object) { // 这里应该算第三种实现方式,然而FullLifecycleObserver不是public,所以不能使用 if (object instanceof FullLifecycleObserver) { return new FullLifecycleObserverAdapter((FullLifecycleObserver) object); } // 我们的第一种方式 if (object instanceof GenericLifecycleObserver) { return (GenericLifecycleObserver) object; } // 通过注解生成的 final Class> klass = object.getClass(); // 将生成的MyLifecycleObserver_LifecycleAdapter放到Map中 int type = getObserverConstructorType(klass); if (type == GENERATED_CALLBACK) { List> constructors = sClassToAdapters.get(klass); if (constructors.size() == 1) { GeneratedAdapter generatedAdapter = createGeneratedAdapter( constructors.get(0), object); return new SingleGeneratedAdapterObserver(generatedAdapter); } GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()]; for (int i = 0; i < constructors.size(); i++) { adapters[i] = createGeneratedAdapter(constructors.get(i), object); } return new CompositeGeneratedAdaptersObserver(adapters); } return new ReflectiveGenericLifecycleObserver(object); }
根据我们传入的对象进行解析,最终返回结果为:GenericLifecycleObserver或者GenericLifecycleObserver的实现类。附获取生成MyLifecycleObserver_LifecycleAdapter代码:
// 通过名称获取 public static String getAdapterName(String className) { return className.replace(".", "_") + "_LifecycleAdapter"; }
最终通过Class.forName方式获得Class。
3.事件分发
Lifecycle的事件分发在ObserverWithState类中:
// 事件分发 void dispatchEvent(LifecycleOwner owner, Event event) { State newState = getStateAfter(event); mState = min(mState, newState); mLifecycleObserver.onStateChanged(owner, event); mState = newState; }
看下哪里调用了dispatchEvent方法:
调用
我们看这个方法,其中一个在addObserver中调用,另外的两个都会通过sync()方法调用:
// happens only on the top of stack (never in reentrance), // so it doesn't have to take in account parents private void sync() { LifecycleOwner lifecycleOwner = mLifecycleOwner.get(); if (lifecycleOwner == null) { Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn't try dispatch " + "new events from it."); return; } // 新的状态和当前状态不一致,则需要进行状态修改 while (!isSynced()) { mNewEventOccurred = false; // no need to check eldest for nullability, because isSynced does it for us. if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) { backwardPass(lifecycleOwner); } Entrynewest = mObserverMap.newest(); if (!mNewEventOccurred && newest != null && mState.compareTo(newest.getValue().mState) > 0) { forwardPass(lifecycleOwner); } } mNewEventOccurred = false; } // 是否状态同步的 private boolean isSynced() { if (mObserverMap.size() == 0) { return true; } // 新的和最后添加的Observer状态一致,并且当前的状态和新状态一致,则已经同步了 State eldestObserverState = mObserverMap.eldest().getValue().mState; State newestObserverState = mObserverMap.newest().getValue().mState; return eldestObserverState == newestObserverState && mState == newestObserverState; }
这里的同步方法用于同步当前Observer的状态,如果新的和最老的Observer的状态不一致或者当前的状态和新的状态不一致时,那么需要进行状态同步。同步包括了向前同步和向后同步。
调用sync()方法一共就两处,一处在addObserver方法,另一处是moveToState方法,而调用moveToState方法也有两处:
@SuppressWarnings("WeakerAccess") @MainThread public void markState(@NonNull State state) { moveToState(state); } public void handleLifecycleEvent(@NonNull Lifecycle.Event event) { State next = getStateAfter(event); moveToState(next); }
handleLifecycleEvent方法有很多处调用:
handleLifecycleEvent调用
看图的话,就可以知道Fragment在不同的生命周期调用了handleLifecycleEvent方法,随便看一个吧:
ON_CREATE
还记得上面说的ReportFragment吗?这里也出现了,我们看下ReportFragment到底做什么的:
// 调用Activity的 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); } } } // 生命周期 @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; }
可以看到,ReportFragment只是作为一个中间层,通过它来分发各种事件!
由于篇幅原因(已经啰嗦了很多了),这里就不写LifecycleDispatcher和ProcessLifecycleOwner了,这两个通过自定义的内容提供者ProcessLifecycleOwnerInitializer进行初始化,并且通过registerActivityLifecycleCallbacks和registerFragmentLifecycleCallbacks注册统一的观察回调。
关于“Android中的Lifecycle有什么用”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“Android中的Lifecycle有什么用”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注创新互联行业资讯频道。
网页标题:Android中的Lifecycle有什么用-创新互联
标题来源:http://hbruida.cn/article/dhpdjg.html