如何使用ProcessLifecycleOwner捕获生命周期事件? [英] How to catch lifecycle events with ProcessLifecycleOwner?

查看:606
本文介绍了如何使用ProcessLifecycleOwner捕获生命周期事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图(至少部分地)确定用户何时关闭应用程序以释放某些连接等.为此,我将ProcessLifecycleOwner与实现LifecycleObserver的应用程序类一起使用.尽管从教程和其他有用的文章中获取了起始代码,但似乎无法检测到任何生命周期事件.

I am trying to (at least partially) determine when an application gets closed by the user to release some connections, etc. To do this, I am using the ProcessLifecycleOwner with my application class implementing LifecycleObserver. Despite taking the starting code from tutorials and other helpful articles, it does not seem to detect any lifecycle events.

大多数代码来自我的应用程序类:

public class App extends Application implements LifecycleObserver {
    @Override
    public void onCreate() {
        super.onCreate();

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

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void created() {
        Log.d("SampleLifeCycle", "ON_CREATE");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void started() {
        Log.d("SampleLifeCycle", "ON_START");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void resumed() {
        Log.d("SampleLifeCycle", "ON_RESUME");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void paused() {
        Log.d("SampleLifeCycle", "ON_PAUSE");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void stopped() {
        Log.d("SampleLifeCycle", "ON_STOP");
    }
}

Gradle中的依赖项

The dependency in Gradle

dependencies {
    //...
    implementation 'android.arch.lifecycle:extensions:1.1.1'
}

到目前为止,无论应用程序进入前台还是后台,此代码都未记录任何形式的事件.

So far, this code has not logged a single event of any sort, whether the app is entering the foreground or the background.

编辑

注意:您需要在清单中声明您的应用程序,以便在自定义应用程序类中起作用的所有内容.

Note: You NEED to declare your application in the Manifest for anything to work in your custom application class.

推荐答案

您需要相应的注释处理器来注意这些注释:

You need the corresponding annotation processor to pay attention to those annotations:

annotationProcessor 'android.arch.lifecycle:compiler:1.1.1'

或者,启用Java 8支持,然后切换到DefaultLifecycleObserver.

Or, enable Java 8 support, and switch to DefaultLifecycleObserver.

这篇关于如何使用ProcessLifecycleOwner捕获生命周期事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆