且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么是生命周期观察器以及如何正确使用它?

更新时间:2022-05-31 03:55:37

您可以使用ProcessLifecycleOwner获取应用程序的LifeCycle并添加一个类作为这些事件的观察者.您可以在应用程序类中实现LifecycleObserver:

You can use ProcessLifecycleOwner to get your Application's LifeCycle and to add a class as an observer of these events. You can implement LifecycleObserver in your Application Class:

public class MyApplication extends MultiDexApplication implements LifecycleObserver

@Override
public void onCreate() {
    super.onCreate();

    ProcessLifecycleOwner.get().getLifecycle().addObserver(this);

}

//添加以下生命周期方法以观察您的应用何时进入后台或进入前台:

// Add these Lifecycle methods to observe when your app goes into the background or to the foreground:

@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void appInResumeState() {
    Toast.makeText(this,"In Foreground",Toast.LENGTH_LONG).show();
}

@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void appInPauseState() {
    Toast.makeText(this,"In Background",Toast.LENGTH_LONG).show();
}

///在build.gradle文件中添加以下内容

// Add the following in your build.gradle file

implementation 'android.arch.lifecycle:extensions:1.1.1'

//也在活动或片段中

您还可以通过创建实现LifecycleObserver的不同组件,然后将活动的生命周期传递给这些组件,来降低代码的复杂性.这样,您就可以将巨大的复杂性分解为不同的组件.

You can also use them to reduce the complexity of code by creating different components which are implementing LifecycleObserver and then pass the lifecycle of activity to these components. This way you can split up the huge complexity to different components.

class MainActivity : AppCompatActivity(), LifecycleObserver {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        ReduceComplexComponent().registerLifecycle(lifecycle)

    }

}

class ReduceComplexComponent : LifecycleObserver{

    registerLifecycle(lifecycle : Lifecycle){
       lifecycle.addObserver(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun resume() {
       Log.d("OnResume","ON_RESUME")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun pause() {
       Log.d("onPause","ON_PAUSE")
    }
}

这样,您可以在单独的组件中侦听活动或片段生命周期事件.

This way you can listen to activity or fragment lifecycle events in separate components.

我们还可以在Activity中手动获取生命周期实例的当前状态,并可以使用其 getCurrentState ()

We can also manually fetch the current state of our lifecycle instance in Activity and that we can do by using its getCurrentState()

状态还具有 isAtLeast ()方法,可用于与当前生命周期状态进行比较

A State also has an isAtLeast() method that we can use to perform comparisons against the current lifecycle state