应用程序被杀死时Android后台服务正在重新启动

标签 android service background-service

我正在开发一个应用程序,其中创建了一个后台服务来收集传感器数据。我从我的 Activity 开始服务:

startService(new Intent(this, MyService.class));

我创建了服务,因此如果应用程序被销毁,后台服务仍会继续收集数据。我试过这个,它在一定程度上奏效了。我的问题是,当我终止应用程序时,服务似乎重新启动,因为调用了 onCreate() 服务和 onStart() 方法。请问有什么方法可以不重启服务吗?

更新:

正如下面的答案所建议的,我在服务中添加了以下方法,但没有运气。

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_NOT_STICKY;
}

最佳答案

这取决于 onStartCommand 中返回的值。

您必须返回 START_NOT_STICKY

根据documentation :

For started services, there are two additional major modes of operation they can decide to run in, depending on the value they return from onStartCommand(): START_STICKY is used for services that are explicitly started and stopped as needed, while START_NOT_STICKY or START_REDELIVER_INTENT are used for services that should only remain running while processing any commands sent to them

简而言之: 如果您返回 START_STICKY,则只要资源可用,就会重新创建服务。如果您返回 START_NOT_STICKY,则必须重新激活发送新 Intent 的服务。

由于所有这些都引发了我的好奇心,我制作了一个示例应用程序来测试它。您可以找到包含所有 sources here 的 zip 有一个 startService 按钮和一个 stopService 按钮可以执行您对它们的期望。 该服务在 onStartCommand 中返回 START_NOT_STICKY。 我在 onCreate、onStartCommand 和 onDestroy 中放置了 toast。

这里会发生什么:

  • 如果我按下开始键,就会调用 onCreate 和 onStart
  • 如果我按下停止键,就会触发 onDestroy
  • 如果我按 start 两次,onCreate 会被调用一次,onStartCommand 会被调用两次

所以它的行为符合人们的预期。

如果我按照您的描述启动服务并终止应用程序,则不会调用 onDestroy,但不会调用 onCreate 或 onStart。

如果我回到应用程序并再次按启动,onCreate 会被调用,这意味着,正如我之前写的,START_NOT_STICKY 会阻止服务自动重启。

我猜你的应用中有其他东西会再次启动服务(可能是待处理的 Intent )。

关于应用程序被杀死时Android后台服务正在重新启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15452935/

相关文章:

iOS 后台服务第一次没有运行

java - 当应用程序关闭时 putExtra 到 Service 类停止

cordova - apache cordova 应用程序中的后台服务

java - 创建一个url字符串以在java中获取一个图标

android - 在 DrawerLayout 上方放置一个 View (在抽屉上方)

android - 如何定期启动服务?

mysql - Puppet 无法在 chroot 环境中运行服务

android - 我想在 android 应用程序中制作后台服务,即使应用程序关闭也应该继续运行

android - 如何循环多个按钮 View ?

android - GCM-App 真的需要唤醒锁吗?