0

I want to update user activity status (Online/Offline) based on Application is running or not. To do so I have used LifecycleEventObserver to Observe the lifecycle inside the Application file.

@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
    Log.e("onStateChanged", "Lifecycle.Event : " + event.name());
    switch (event.name()) {
        case "ON_START":
        case "ON_RESUME":
            setStatus(true);
            break;
        case "ON_STOP":
        case "ON_PAUSE":
            setStatus(false);
            break;
    }
}

It works fine in happy flow as shown in this .Gif file(When switching to recent apps it logs Lifecycle events ON_PAUSE, ON_STOP inside onStateChanged).

  • Issue case:

But I have found one case in which the application fails to observe when the application stops running. As shown in this .Gif file (When switching to recent apps and the user kills an application from recent apps rapidly, it does not get a chance to observe the lifecycle events. So here, It is not able to log Lifecycle events ON_PAUSE, ON_STOP inside onStateChanged).

I have also tried DefaultLifecycleObserver but it also behaves the same way.

@Override
public void onStart(@NonNull LifecycleOwner owner) {
    Log.e("Globals", "onStart");
    setStatus(true);
}

@Override
public void onCreate(@NonNull LifecycleOwner owner) {
    Log.e("Globals", "onCreate");
}

@Override
public void onResume(@NonNull LifecycleOwner owner) {
    Log.e("Globals", "onResume");
    setStatus(true);
}

@Override
public void onPause(@NonNull LifecycleOwner owner) {
    Log.e("Globals", "onPause");
    setStatus(false);
}

@Override
public void onStop(@NonNull LifecycleOwner owner) {
    Log.e("Globals", "onStop");
    setStatus(false);
}

@Override
public void onDestroy(@NonNull LifecycleOwner owner) {
    Log.e("Globals", "onDestroy");
    setStatus(false);
}
greg-449
  • 109,219
  • 232
  • 102
  • 145

1 Answers1

0

Unfortunately, this behavior is by design. When the user kills the app from the Recents menu, it's the same as force-stopping it from the phone's settings -- it's not meant to be graceful, and the usual lifecycle methods aren't called.

But on the broader subject of trying to detect if the app is actually running, you can just implement a "heartbeat" signal that the app sends out periodically (either to a web server, or to another app). And if that heartbeat signal stops being received, then the app has been shut down

user496854
  • 6,461
  • 10
  • 47
  • 84