【问题标题】:IntentService is killed after 30 mins when my app is in background当我的应用程序处于后台时,IntentService 在 30 分钟后被杀死
【发布时间】:2013-08-12 08:42:59
【问题描述】:

我创建了一个自定义后台服务,它正在扩展 IntentService。当我的应用程序通过 .startService() 进入后台时,我正在调用此类。首先 onStartCommand 在我返回 START_STICKY 的地方被调用(就像我已经阅读了一些其他帖子以保持我的服务处于活动状态,并在因内存不足而被杀死时重新创建)。之后,我正在实现 onHandleIntent(intent) 方法,在该方法中我从调用者意图中获取附加信息,并且在这里我启动了一个 Timer 以每分钟运行一次并执行简单的代码。但这里的问题是,当应用程序处于后台时,30 分钟后我的服务被终止并且没有重新创建。这是我的代码的一部分,所以任何建议都是完美的。

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

@Override
protected void onHandleIntent(Intent workIntent) {
    //here I'm initializing the Timer
}

class UpdateTimeTask2 extends TimerTask {
     public void run() {
         backgroundTimer();//here I'm doing some simple coding
     }
}

【问题讨论】:

  • IntentService 不是为了那个.. 使用 Service 代替
  • 好的,我现在就试试。

标签: android intentservice background-service


【解决方案1】:

所以,正如 Kumar 所说,我应该扩展 Service 而不是 IntentService。服务的调用与 IntentService 的调用相同,唯一的区别是 Service 类所需的未实现的方法。此外,我正在使用 Handler 的 postDelayed 方法而不是 Timer,并且在 onStartComand 中我正在返回 START_STICKY。所以服务根本没有被杀死。有用的代码可以在herehere 找到。我希望这会有所帮助。

【讨论】:

    【解决方案2】:

    在这种情况下,您只需要一个普通的服务和一个处理程序。正如 Pankaj 所写,IntentServices 不是长期运行的设计者。然后,您可以使用 Handler 的 postDelayed 方法每分钟执行一次代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      • 2015-05-15
      相关资源
      最近更新 更多