AAC---LifeCycle

2018-06-22  本文已影响24人  None_Ling

LifeCycle介绍

LifeCycle最主要解决的问题是在Activity或者Fragment的生命周期中功能与页面状态之间的关系,以及对于功能太多时,onResume以及onPause等生命周期函数太臃肿产生的。

LifeCycle的使用

  1. 根据需要添加LifeCycle的配置项
dependencies {
    def lifecycle_version = "1.1.1"

    // ViewModel and LiveData
    implementation "android.arch.lifecycle:extensions:$lifecycle_version"
    // alternatively - just ViewModel
    implementation "android.arch.lifecycle:viewmodel:$lifecycle_version" // use -ktx for Kotlin
    // alternatively - just LiveData
    implementation "android.arch.lifecycle:livedata:$lifecycle_version"
    // alternatively - Lifecycles only (no ViewModel or LiveData).
    //     Support library depends on this lightweight import
    implementation "android.arch.lifecycle:runtime:$lifecycle_version"

    annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version"
    // alternately - if using Java8, use the following instead of compiler
    implementation "android.arch.lifecycle:common-java8:$lifecycle_version"

    // optional - ReactiveStreams support for LiveData
    implementation "android.arch.lifecycle:reactivestreams:$lifecycle_version"

    // optional - Test helpers for LiveData
    testImplementation "android.arch.core:core-testing:$lifecycle_version"
}
  1. 实现LifecycleObserver 接口,定义该功能能力,并且通过OnLifecycleEvent标注该能力对应的生命周期
public class LifeCycleListener implements LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void startLocation() {
      // Do Something
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void stopLocation() {
      // Do Something
    }
}
  1. 在Activity/Fragment中注册Observer
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DataBindingUtil.setContentView(this, R.layout.activity_main);
        getLifecycle().addObserver(new LifeCycleListener());
    }

}

PS:

DIV实现LifeCycle

在26.1.0之后Support Lib中的Activity以及Fragments都已经实现了LifeCycleOwner接口,如果没有使用AppComaptActivity的话,可以自己实现一套LifeCycle。

将Activity与Fragment实现LifeCycleOwner接口,并且在内部创建LifecycleRegistry对象,在生命周期的回调函数中标记当前状态即可。

public class MyActivity extends Activity implements LifecycleOwner {
    private LifecycleRegistry mLifecycleRegistry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLifecycleRegistry = new LifecycleRegistry(this);
        mLifecycleRegistry.markState(Lifecycle.State.CREATED);
    }

    @Override
    public void onStart() {
        super.onStart();
        mLifecycleRegistry.markState(Lifecycle.State.STARTED);
    }

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

LifeCycle的最佳实践

参考资料

Handling lifecycles with lifecycle-aware components

上一篇 下一篇

猜你喜欢

热点阅读