[英]How can I detect If my android application is Destroyed/Paused/Stopped without fail?
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 .
为此,我使用LifecycleEventObserver来观察应用程序文件中的生命周期。
@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 ).如此.Gif 文件所示,它在快乐流程中运行良好(当切换到最近的应用程序时,它会在onStateChanged内记录生命周期事件 ON_PAUSE、ON_STOP)。
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 ).
如这个.Gif文件所示(当切换到最近的应用程序并且用户从最近的应用程序中快速杀死一个应用程序时,它没有机会观察生命周期事件。所以这里,它无法记录生命周期事件ON_PAUSE,ON_STOP在onStateChanged内)。
I have also tried DefaultLifecycleObserver but it also behaves the same way.我也尝试过DefaultLifecycleObserver但它的行为方式也相同。
@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);
}
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).但在尝试检测应用程序是否实际运行的更广泛主题上,您可以实现应用程序定期发送的“心跳”信号(发送到 web 服务器或另一个应用程序)。 And if that heartbeat signal stops being received, then the app has been shut down
如果停止接收该心跳信号,则该应用程序已关闭
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.