Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch lifecycle events with ProcessLifecycleOwner?

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.

Most of the code came from this example.

My application class:

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

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.

EDIT

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

like image 932
AshesToAshes Avatar asked Jun 26 '19 20:06

AshesToAshes


People also ask

How Mvvm is lifecycle-aware?

Lifecycle Awareness: ViewModel objects are also lifecycle-aware. They are automatically cleared when the Lifecycle they are observing gets permanently destroyed. Data Sharing: Data can be easily shared between fragments in an activity using ViewModels .

Which lifecycle method is called to give an activity focus?

There are two lifecycle methods that handle when the activity is paused and when it becomes active again: onPause() and onResume() . onPause() gets called when your activity is visible but another activity has the focus. onResume() is called immediately before your activity is about to start interacting with the user.


1 Answers

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

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

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

like image 192
CommonsWare Avatar answered Oct 11 '22 18:10

CommonsWare