半夜三更不小心看了一个公众号。
不小心发现了这个Lifecycle...
Lifecycle-Aware 思想是Google官方提出来的概念:赋予普通类自动感知生命周期的能力。
Lifecycle实现的一个重要目的,是实现Android的与Activity和Fragment生命周期相关的逻辑控制进一步的解耦。
优化一:当Activity进入onDestroy时,自动取消网络请求返回
优化二:自动将网络请求时机提前到View渲染之前,提高页面打开速度
优化三:MVP改进,让Presenter和View自动bind/unBind
用法很简单
maven
allprojects {
repositories {
maven { url 'https://maven.google.com' } //添加此行
jcenter()
}
}
//For Lifecycles, LiveData, and ViewModel
compile "android.arch.lifecycle:runtime:1.0.3"
compile "android.arch.lifecycle:extensions:1.0.0"
annotationProcessor "android.arch.lifecycle:compiler:1.0.0"
//For Room
compile "android.arch.persistence.room:runtime:1.0.0"
annotationProcessor "android.arch.persistence.room:compiler:1.0.0"
public class HttpRequest implements LifecycleObserver {
public HttpRequest() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
public void onAny() {
Log.i("Tongson", "ON_ANY");
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate() {
Log.i("Tongson", "ON_CREATE");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart() {
Log.i("Tongson", "ON_START");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {
Log.i("Tongson", "ON_RESUME");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause() {
Log.i("Tongson", "ON_PAUSE");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop() {
Log.i("Tongson", "ON_STOP");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
Log.i("Tongson", "onDestroy");
}
}
HttpRequest httpRequest = new HttpRequest();
getLifecycle().addObserver(httpRequest);
源码:
https://chaosleong.github.io/2017/05/27/How-Lifecycle-aware-Components-actually-works/
https://developer.android.com/topic/libraries/architecture/index.html
https://developer.android.com/topic/libraries/architecture/lifecycle.html
https://developer.android.com/topic/libraries/architecture/livedata.html
https://developer.android.com/topic/libraries/architecture/viewmodel.html