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

What is lifecycle observer and how to use it correctly?

我在 Android 中阅读了有关新架构组件的信息。所以,我想问一下什么是生命周期观察者,我们为什么需要它们?在什么情况下有用? 感谢您的回答!

您可以使用 ProcessLifecycleOwner 获取应用程序的生命周期并添加一个 class 作为这些事件的观察者。您可以在您的应用程序中实现 LifecycleObserver Class:

public class MyApplication extends MultiDexApplication implements LifecycleObserver

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

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

}

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

@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 文件中添加以下内容

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

//也在活动或片段中

您还可以使用它们来降低代码的复杂性,方法是创建实现 LifecycleObserver 的不同组件,然后将 activity 的生命周期传递给这些组件。这样您就可以将巨大的复杂性分解为不同的组件。

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")
    }
}

这样您就可以在单独的组件中监听 activity 或片段生命周期事件。

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

State 也有一个 isAtLeast() 方法,我们可以使用它来与当前生命周期状态进行比较

LifeCycleObserver is part of Google released Android Jetpack LifeCycle Architecture components, and it is an interface that allows you to observe a LifeCycle-aware observable component, typically a LifeCycleOwner (Activity/Fragment), in order to interact with the LifeCycle events and states 关联到此组件;这样您就可以监控前台和后台生命周期事件。

以下是一些具有典型用法的有用链接

派对可能有点晚了,但另一个很好的生命周期用例(除了明显的 ViewModel 东西)是让应用程序的许多组件在相关 activity 正在被摧毁,或者只是在屏幕之外。

例如,我有一个创建对话框的静态工厂,并且使用生命周期我可以关闭对话框而不用像 activity 这样的旧东西弄乱主机=12=] 和 void onPause(){ ... if (mDialog !null && mDialog.isShowing()) mDialog.cancel() }

一些代码:

DialogUtils.java:

public static void showConfirmDialog(Lifecycle lifecycle, String title, String msg, Runnable okRunnable) {
    AlertDialog dialog = AlertDialog.Builder(mAppContext)
    /* configuration stuff ... */
        .build();

    dialog.show();

    lifecycle.addObserver(new LifecycleObserver() {
          @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
          public void cancelDialog() {
            if (dialog.isShowing()) { // if not already dismissed by main-button tap 
              dialog.cancel();
            }
          }
    });
}

MyActivity.java:

public class MyActivity extends AppCompatActivity {

    /* stuff... onCreate()... other stuff... */

    private void confirmDeleteUser(User user){
        DialogUtils.showConfirmDialog(
            MyActivity.this.getLifecycle(), // all activities & fragment have lifecycles
            "Confirm Delete",
            "Action cannot be undone. Sure to continue?",
            new Runnable() { /* stuff... */ }
        );
        // Voilà! 
        // activity no needs to store reference to the dialog and cancel manually on pause
        // it's a fire-and-forget action
    }
}

您使用它们是为了减少由于您的应用 Lifecycle events 而引起的组件回调和清理。例如,你有一个 Handler/Runnable 是 运行 来自某处的 Thread 并且你需要一些 callbacks/interfaces 以便在 onStop() 被调用;因此使用新的 "Jetpack LifeCycle Architecture components" 你可以使你的 component/class "lifecycle-aware" 从而从 Activity/Fragment 使用它轻松控制它!

更多信息如上所述:https://developer.android.com/topic/libraries/architecture/lifecycle

lifecycle-extensions API 已弃用。

lifecycle-extensions Artifact Deprecation: With the above deprecation of ViewModelProviders.of(), this release marks the deprecation of the last API in lifecycle-extensions and this artifact should now be considered deprecated in its entirety. We strongly recommend depending on the specific Lifecycle artifacts you need (such as lifecycle-service if you’re using LifecycleService and lifecycle-process if you’re using ProcessLifecycleOwner) rather than lifecycle-extensions as there will not be a future 2.3.0 release of lifecycle-extensions.

如果您想继续使用ProcessLifecycleOwner, 建议添加这个依赖:

implementation "androidx.lifecycle:lifecycle-process:2.2.0"

参考:
https://developer.android.com/jetpack/androidx/releases/lifecycle#version_220_3

https://androidx.tech/artifacts/lifecycle/lifecycle-extensions/

https://developer.android.com/reference/androidx/lifecycle/ProcessLifecycleOwner

@OnLifecycleEvent 弃用 因此许多曾经在这里有用的答案不再有用。如果您目前尚未使用 Java 8,则需要先更新 build.gradle。我们现在可以使用 DefaultLifecycleObserverLifecycleEventObserver。请参阅下面的示例。

首先,您可以使用 ProcessLifecycleOwner 获取应用程序的生命周期:

ProcessLifecycleOwner.get().getLifecycle()

DefaultLifecycleObserver:

lifecycle.addObserver(object: DefaultLifecycleObserver {
    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        TODO()
    }
    override fun onPause(owner: LifecycleOwner) {
        TODO()
        super.onPause(owner)
    }
})

LifecycleEventObserver:

lifecycle.addObserver(object: LifecycleEventObserver {
    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when (event) {
            Lifecycle.Event.ON_RESUME -> TODO()
            Lifecycle.Event.ON_PAUSE -> TODO()
            else -> { }
        }
    }
})

如何更新到 Java 8 以及为什么 OnLifecycleEvent 被弃用的解释: