美文网首页我爱编程
Lifecycle-Aware Components

Lifecycle-Aware Components

作者: zztigyk | 来源:发表于2018-04-16 15:49 被阅读0次

    The android.arch.lifecycle package 提供了构建 lifecycle-aware的类和接口。lifecycle-aware可让您构建生命周期感知组件,这些组件可以根据活动或片段的当前生命周期状态自动调整其行为。
    Note: 导入 android.arch.lifecycle 到您的安卓项目, 详情查看: adding components to your project.

    Lifecycle


    Lifecycle是一个持有组件(Activity或者Fragment)生命周期状态的类,并允许其他对象观察此状态。

    Lifecycle 使用两个主要枚举来跟踪其关联组件的生命周期状态:

    Event

    Event是从framework 和Lifecycle类派发的生命周期事件。这些事件映射到activities 和 fragments中的回调事件。

    State

    由Lifecycle对象跟踪的组件的当前组件的生命周期状态。

    image.png
    public class MyObserver implements LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void connectListener() {
        ...
    }
    
    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void disconnectListener() {
        ...
    }
    }
    //aLifecycleOwner一般是实现了LifecycleOwner的类,比如Activity/Fragment,最新的Activity已经实现此接口
    myLifecycleOwner.getLifecycle().addObserver(new MyObserver());
    

    LifecycleOwner


    LifecycleOwner is a single method interface that denotes that the class has a Lifecycle. It has one method, getLifecycle(), which must be implemented by the class. If you're trying to manage the lifecycle of a whole application process instead, see ProcessLifecycleOwner.

    This interface abstracts the ownership of a Lifecycle from individual classes, such as [Fragment](https://developer.android.com/reference/android/support/v4/app/Fragment.html) and [AppCompatActivity](https://developer.android.com/reference/android/support/v7/app/AppCompatActivity.html), and allows writing components that work with them. Any custom application class can implement the LifecycleOwner interface.

    Components that implement LifecycleObserver work seamlessly with components that implement LifecycleOwner because an owner can provide a lifecycle, which an observer can register to watch.

    For the location tracking example, we can make the MyLocationListener class implement LifecycleObserver and then initialize it with the activity'sLifecycle in the [onCreate()](https://developer.android.com/reference/android/app/Activity.html#onCreate(android.os.Bundle)) method. This allows the MyLocationListener class to be self-sufficient, meaning that the logic to react to changes in lifecycle status is declared in MyLocationListener instead of the activity. Having the individual components store their own logic makes the activities and fragments logic easier to manage.

    相关文章

      网友评论

        本文标题:Lifecycle-Aware Components

        本文链接:https://www.haomeiwen.com/subject/mzqekftx.html