Jetpack -Lifecycle
2019-06-24 本文已影响0人
Active_Loser
一、简介
Lifecycle :Lifecycle 包含有关Activity与Fragment生命周期状态的信息,并允许其他对象观察此状态,主要作用于避免内存泄漏和观察组件(Activtiy、Fragment)的生命周期状态。
二、基本使用
1、创建观察者
public class MyObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop() {
}
}
// 使用java8,可以实现DefaultLifecycleObserver并添加 androidx.lifecycle:common-java8:<version>
class MyObserver implements DefaultLifecycleObserver {
@Override
public void onCreate(LifecycleOwner owner) {
}
}
2、使用
2.1 AppCompatActivity中
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLifecycle().addObserver(new MyObserver());
}
}
2.2 Activity中
ublic class MainActivity extends Activity implements LifecycleOwner {
private static final String TAG = "MainActivity";
private LifecycleRegistry mLifecycleRegistry;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLifecycleRegistry = new LifecycleRegistry(this);
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
//添加观察者
getLifecycle().addObserver(new MyObserver());
}
@Override
protected void onStart() {
super.onStart();
mLifecycleRegistry.markState(Lifecycle.State.STARTED);
}
@Override
@NonNull
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
Lifecycle的优势我们以及结合MVP使用,可以去看MVPArms框架怎么结合Lifecycle使用。