Google 官方发布了Android 框架组件库(Android Architecture Components),目的为了帮助开发者开发更健壮,便于测试和维护的应用。框架主要用来管理UI组件(Activity或Fragment)的生命周期,提供持久化数据的方式。
问题一:在简化Activity或Fragment(下称UI组件)中代码逻辑时,我们发现,与生命周期相关的逻辑很难从UI组件中迁移出去,导致UI组件部分关键生命周期回调中的代码很臃肿(强迫症重度患者),十分不易维护。
问题二: 由于移动设备资源有限,Android系统随时都可能会杀死一些应用程序(按照一定的规则或者说根据应用的状态和其优先级),以腾出空间给新的应用。此时,UI组件的生命周期(这里主要是指销毁)就不在我们的控制之下了,所以,如果我们将用户数据直接存储在UI组件中,又没做一些比较麻烦的保护措施,那么组件中的用户数据就GG了。
Lifecycle:帮助我们轻松的管理UI组件的生命周期,当组件的生存状态改变时,可以避免内存泄漏的问题,并且能轻松的将数据重新加载到UI中。
LiveData:一个数据持有类,持有数据并且这个数据可以被观察(一般观察者就是UI组件啦),当其持有的数据发生变化时,能通知到他的观察者们(嗯,这很强)。
ViewModel:用于存储UI相关数据(LiveData咯),作为UI组件和数据的桥梁,将数据和组件分离,完成了持久化和保护数据的任务。
Room:谷歌推出的一个SQLite对象映射库,使用注解,极大简化数据库的操作。还能在编译时检查SQLite语句,可以返回RxJava,Flowable和LiveData Observable。
架构图:下面这张图是Android架构组件完整的架构图,其中表示了的架构组件的所有模块以及它们之间如何交互
框架补充:如果不满足官方的库其实可以自己实现。比如LiveData在某些情况下可使用RxJava代替。数据层官方推荐使用Room或者Realm或者其他SQLite ORM等都可以。网络请求推荐使用Retrofit。各层之间的耦合推荐使用服务发现者模式(Service Locator)或者依赖注入(DI),推荐Dagger2。
架构组件较多,本文主要讲解Lifecycle,其他组件会在后续的文章中介绍。
UI组件的生命周期是由Android系统或者framework层代码管理的,我们是无法控制的,只能在生命周期的回调方法里(onCreate等)做一些处理。
很多时候,我们的很多操作都需要写在生命周期的回调方法中,比如,注册或者销毁(EventBus,友盟之类的三方库),依赖其他组件(Service或者Broadcast)等。示例代码如下
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
}
}
这样写,看上去,嗯,没毛病,但是在真实的项目中,一个关键的UI组件的生命周期回调方法里,那代码量是相当可观的(onCreate代码分分钟破百行给你看),所以这就使得他们难以维护。
此外,由于我们无法控制生命周期,假如我们在例如onStart中做了一些耗时操作(检查网络状态啊,检查配置文件数据啊,检查数据库啊),如果在这些耗时操作还没执行完,组件就已经完了(onStop或者onDestroy),我们就一脸懵逼了啊(药丸,内存泄漏是小,搞不好会崩),示例代码如下:
class MyActivity extends AppCompatActivity {
private MyLocationListener myLocationListener;
public void onCreate(...) {
myLocationListener = new MyLocationListener(this, location -> {
// update UI
});
}
@Override
public void onStart() {
super.onStart();
Util.checkUserStatus(result -> {
// what if this callback is invoked AFTER activity is stopped?
if (result) {
myLocationListener.start();
}
});
}
@Override
public void onStop() {
super.onStop();
myLocationListener.stop();
}
}
怪我假如太多?哼哼,项目中假如可能比你想象的多。推销进入高潮,那么为了解决以上问题,我们就要用Lifecycle组件。
allprojects {
repositories {
google()
jcenter()
}
}
dependencies {
def lifecycle_version = "2.0.0"
// alternatively - Lifecycles only (no ViewModel or LiveData).
// Support library depends on this lightweight import
compile "android.arch.lifecycle:runtime:$lifecycle_version"
// ViewModel and LiveData
compile "android.arch.lifecycle:extensions:$lifecycle_version"
}
public class MyObserver7 implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate() {
Log.d(TAG, "onCreate");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart() {
Log.d(TAG, "onStart");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {
Log.d(TAG, "onResume");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause() {
Log.d(TAG, "onPause");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop() {
Log.d(TAG, "onStop");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
Log.d(TAG, "onDestroy");
}
}
注意:如果使用本姿势,你需要支持Java8的组件。
implementation "android.arch.lifecycle:common-java8:1.0.0"
public class MyObserver8 implements DefaultLifecycleObserver {
@Override
public void onCreate(@NonNull LifecycleOwner owner) {
Log.d(TAG, "onCreate");
}
@Override
public void onStart(@NonNull LifecycleOwner owner) {
Log.d(TAG, "onStart");
}
@Override
public void onResume(@NonNull LifecycleOwner owner) {
Log.d(TAG, "onResume");
}
@Override
public void onPause(@NonNull LifecycleOwner owner) {
Log.d(TAG, "onPause");
}
@Override
public void onStop(@NonNull LifecycleOwner owner) {
Log.d(TAG, "onStop");
}
@Override
public void onDestroy(@NonNull LifecycleOwner owner) {
Log.d(TAG, "onDestroy");
}
}
至于原因嘛,官网注释镇楼,自行翻译吧,看情形,Google推荐使用Java8啊:
/ * If you use Java 8 Language, then observe events with {@link DefaultLifecycleObserver}.
* To include it you should add {@code "android.arch.lifecycle:common-java8:"} to your
* build.gradle file.
*
* class TestObserver implements DefaultLifecycleObserver {
* {@literal @}Override
* public void onCreate(LifecycleOwner owner) {
* // your code
* }
* }
*
* If you use Java 7 Language, Lifecycle events are observed using annotations.
* Once Java 8 Language becomes mainstream on Android, annotations will be deprecated, so between
* {@link DefaultLifecycleObserver} and annotations,
* you must always prefer {@code DefaultLifecycleObserver}.
*
* class TestObserver implements LifecycleObserver {
* {@literal @}OnLifecycleEvent(ON_STOP)
* void onStopped() {}
* }
*
* /
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 直接调用getLifecycle(),添加Observer
getLifecycle().addObserver(new MyObserver7());
getLifecycle().addObserver(new MyObserver8());
}
}
public class BaseActivity extends Activity implements LifecycleOwner {
private LifecycleRegistry mLifecycleRegistry;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLifecycleRegistry = new LifecycleRegistry(this);
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
mLifecycleRegistry.addObserver(new TestObserver());
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
@Override
public void onStart() {
super.onStart();
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
}
@Override
public void onResume() {
super.onResume();
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
}
@Override
public void onPause() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
super.onPause();
}
@Override
public void onStop() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
super.onStop();
}
@Override
public void onDestroy() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
super.onDestroy();
}
}
至此,Lifecycle基本用法演示完毕,嗯,很方便。
Lifecycle:是一个持有UI组件对应生命周期状态信息的类,并允许其他对象观察此类状态。他使用两个主要的枚举来跟踪其关联组件的生命周期。
枚举1:Event:从框架和Lifecycle类派发的生命周期事件。这些事件映射到UI组件中的生命周期回调事件。
枚举2:State:由Lifecycle对象跟踪的组件的当前状态。
Lifecycle将Activity的生命周期函数对应成State,生命周期改变,会造成State改变,而State变化将触发Event事件,从而被LifecycleObser接收。下图是UI组件生命周期变换过程中State和Event关系图:
LifecycleOwner:Lifecycle持有者,实现该接口的类持有生命周期状态信息的类(Lifecycle对象),生命周期状态信息改变会被其注册的观察者LifecycleObserver观察到并触发其对应的事件。
LifecycleObserver:Lifecycle观察者,实现该接口的类,被注册后,LifecycleObserver便可以观察到Lifecycle的生命周期事件。
/**
* 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.
*
* @see Lifecycle
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
@NonNull
Lifecycle getLifecycle();
}
/**
* Marks a class as a LifecycleObserver. It does not have any methods, instead, relies on
* {@link OnLifecycleEvent} annotated methods.
*
* @see Lifecycle Lifecycle - for samples and usage patterns.
*/
@SuppressWarnings("WeakerAccess")
public interface LifecycleObserver {
}
/**
* Custom list that keeps observers and can handle removals / additions during traversal.
*
* Invariant: at any moment of time for observer1 & observer2:
* if addition_order(observer1) < addition_order(observer2), then
* state(observer1) >= state(observer2),
*/
private FastSafeIterableMap mObserverMap =
new FastSafeIterableMap<>();
/**
* The provider that owns this Lifecycle.
* Only WeakReference on LifecycleOwner is kept, so if somebody leaks Lifecycle, they won't leak
* the whole Fragment / Activity. However, to leak Lifecycle object isn't great idea neither,
* because it keeps strong references on all other listeners, so you'll leak all of them as
* well.
*/
private final WeakReference mLifecycleOwner;
/**
* Creates a new LifecycleRegistry for the given provider.
*
* You should usually create this inside your LifecycleOwner class's constructor and hold
* onto the same instance.
*
* @param provider The owner LifecycleOwner
*/
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
}
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初始状态是INITIALIZED,当前状态是RESUMED,需要将INITIALIZED到RESUMED之间的
// 所有事件分发给Observer
//
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
pushParentState(statefulObserver.mState);
statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
popParentState();
targetState = calculateTargetState(observer);
}
......
}
删除时就很简单了
@Override
public void removeObserver(@NonNull LifecycleObserver observer) {
// we consciously decided not to send destruction events here in opposition to addObserver.
// Our reasons for that:
// 1. These events haven't yet happened at all. In contrast to events in addObservers, that
// actually occurred but earlier.
// 2. There are cases when removeObserver happens as a consequence of some kind of fatal
// event. If removeObserver method sends destruction events, then a clean up routine becomes
// more cumbersome. More specific example of that is: your LifecycleObserver listens for
// a web connection, in the usual routine in OnStop method you report to a server that a
// session has just ended and you close the connection. Now let's assume now that you
// lost an internet and as a result you removed this observer. If you get destruction
// events in removeObserver, you should have a special case in your onStop method that
// checks if your web connection died and you shouldn't try to report anything to a server.
mObserverMap.remove(observer);
}
/**
* 处理生命周期事件
*/
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
/**
* 改变状态
*/
private void moveToState(State next) {
if (mState == next) {
return;
}
mState = next;
......
sync();
......
}
/**
* 同步Observer状态,并分发事件
*/
private void sync() {
LifecycleOwner lfecycleOwner = 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;
// State中,状态值是从DESTROYED-INITIALIZED-CREATED-STARTED-RESUMED增大
// 如果当前状态值 < Observer状态值,需要通知Observer减小状态值,直到等于当前状态值
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
Entry newest = mObserverMap.newest();
// 如果当前状态值 > Observer状态值,需要通知Observer增大状态值,直到等于当前状态值
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
/**
* 向前传递事件,对应图中的INITIALIZED -> RESUMED
* 增加Observer的状态值,直到状态值等于当前状态值
*/
private void forwardPass(LifecycleOwner lifecycleOwner) {
Iterator> ascendingIterator =
mObserverMap.iteratorWithAdditions();
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
Entry 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();
}
}
}
/**
* 向后传递事件,对应图中的RESUMED -> DESTROYED
* 减小Observer的状态值,直到状态值等于当前状态值
*/
private void backwardPass(LifecycleOwner lifecycleOwner) {
Iterator> descendingIterator =
mObserverMap.descendingIterator();
while (descendingIterator.hasNext() && !mNewEventOccurred) {
Entry 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));
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
}
mLifecycleObserver = Lifecycling.getCallback(observer);
static GenericLifecycleObserver getCallback(Object object) {
if (object instanceof FullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
}
if (object instanceof GenericLifecycleObserver) {
return (GenericLifecycleObserver) object;
}
......
}
嗯,上文中提到的第二个实现LifecycleObserver的姿势用的是DefaultLifecycleObserver,这个接口正好是继承FullLifecycleObserver的,所以,我再看下FullLifecycleObserverAdapter干了啥:
class FullLifecycleObserverAdapter implements GenericLifecycleObserver {
private final FullLifecycleObserver mObserver;
FullLifecycleObserverAdapter(FullLifecycleObserver observer) {
mObserver = observer;
}
@Override
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
switch (event) {
case ON_CREATE:
mObserver.onCreate(source);
break;
case ON_START:
mObserver.onStart(source);
break;
case ON_RESUME:
mObserver.onResume(source);
break;
case ON_PAUSE:
mObserver.onPause(source);
break;
case ON_STOP:
mObserver.onStop(source);
break;
case ON_DESTROY:
mObserver.onDestroy(source);
break;
case ON_ANY:
throw new IllegalArgumentException("ON_ANY must not been send by anybody");
}
}
}
嗯,代码很简答,这样,整体就通了啊,数目对上了~哈哈哈
Support Library 26.1.0 及其以后的版本,Activity 和Fragment 已经实现了LifecycleOwner接口,所以,我们可以直接在Activity和Fragment中使用getLifecycle()方法来获取Lifecycle对象,来添加观察者监听。下图中可以看到,源码中直接在Fragment或Activity中直接创建了一个LifecycleRegistry类的实例,由于Fragment或Activity实现了LifecycleOwner接口,所以可以直接使用this关键字将自身作为参数。一般我们会用带有生命周期的类来实现LifecycleOwner接口。
Fragment持有LifecycleRegistry类的实例后,实际上在Fragment对应的生命周期内,都会发送对应的生命周期事件给内部的LifecycleRegistry对象处理:
看源码我们会发现,在Activity的performXXX()类似方法中,没有找到mLifecycleRegistry.handleLifecycleEvent()方法的调用。其实新版本的AppCompatActivity最终也是通过调用Fragment中的这些方法来发送通知的,我们来看一下(AppCompatActivity继承自SupportActivity):
public class SupportActivity extends Activity implements LifecycleOwner {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
}
嗯,有点意思,我们再看下ReportFragment干了啥:
public class ReportFragment extends Fragment {
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();
}
}
@Override
public void onStart() {
super.onStart();
dispatchStart(mProcessListener);
dispatch(Lifecycle.Event.ON_START);
}
// ...... 其他生命周期也是同样调用了dispatch(Lifecycle.Event.xxx)分发事件
@Override
public void onPause() {
super.onPause();
dispatch(Lifecycle.Event.ON_PAUSE);
}
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);
}
}
}
}
所以,Android藏了一手啊,添加了一个没有页面的Fragment来完成Activity的生命周期事件的分发。
为什么不直接在SupportActivity的生命周期函数中给Lifecycle分发生命周期事件,而是要加一个Fragment呢?
因为不是所有的页面都继承AppCompatActivity,为了兼容非AppCompatActivity,所以封装一个同样具有生命周期的Fragment来给Lifecycle分发生命周期事件。
找了一位大神的总结图: