如何在Android应用被杀死之前执行代码 [英] How to execute code before Android app is killed

查看:1241
本文介绍了如何在Android应用被杀死之前执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Android应用程序,可连接到周围的设备当前正在运行同一应用程序,即使在后台运行 .

I have an Android app that connects to surrounding devices currently running the same app, even if in background.

为此,我使用WiF-Direct宣传我当前正在运行所述应用程序的事实.

To do this, I use WiF-Direct to advertise the fact that I am currently running said application.

因此,一旦应用被终止,我就必须停止对此进行宣传.

Therefore I need to stop advertising this as soon as the app is killed.

  • onDestroy()无法使用,因为不能保证会被调用.
  • 由于应用程序仍在运行,因此无法使用
  • onStop()onPause().
  • onDestroy() cannot be used since it is not guaranteed to be called.
  • onStop() and onPause() cannot be used since the app is still running.

我该如何实现?

当前,即使关闭或终止了该应用程序,该服务仍在发布.

Currently the service is still being advertised even when the application is closed/killed.

推荐答案

您应该可以通过服务来做到这一点.

You should be able to do this with a Service.

启动应用程序时启动服务. 覆盖onTaskRemoved方法

Start a service when your app was started. Override the onTaskRemoved method

@Override
public void onTaskRemoved(Intent rootIntent)
{
}

在此方法中,您必须执行的操作. 可以在以下位置找到更详细的答案:如何知道我的应用何时被杀了?(2个答案)

In this method do what you have to do. More detailed answer can be found here: How to know when my app has been killed? (2 answer)

这篇关于如何在Android应用被杀死之前执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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