【问题标题】:Running a long running service运行长时间运行的服务
【发布时间】:2017-10-20 21:01:47
【问题描述】:

我编写了一项服务,该服务从基于 CRM 的 Web 服务中获取数据并将其放入手机上的数据库中。现在这个服务必须每 3 小时运行一次,所以它可以在 CRM 和 android 数据库之间同步数据。

现在要让该服务自行运行,我正在使用警报管理器并让 Web 服务自行“启动”。

Intent intent = new Intent(ServiceClass.this, ServiceClass.class);
PendingIntent pintent = PendingIntent.getService(ServiceClass.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 10800*1000, pintent);

此服务需要在重启后启动,为此我使用method outlined here..

我只是想知道我是否走在正确的道路上,或者我是否犯了错误,或者是否有更好的方法来做到这一点。我没有太多使用Android,只需要一些指示。谢谢!

【问题讨论】:

  • 你用的是什么服务,希望是IntentService
  • @tyczj 我正在使用一个实现服务的类。如果它是一个矫枉过正,我会使用 IntentService

标签: android architecture android-service


【解决方案1】:

是的,您走在正确的道路上。警报管理器非常可靠,专门用于此目的 - 安排未来的任务(重复和非重复)。

我同意@tyczj,您绝对应该将您的ServiceClass 定义为IntentServiceIntentService 是 Service 的子类,它在后台运行,专门设计用于执行特定任务,然后在完成后自行终止。它非常适合下载数据和后台同步。

它也很容易实现,您很可能只需要重写一个方法 - onHandleIntent - 这是服务启动时调用的方法。

要在重新启动时重新安排任务,我使用该帖子中概述的方法。希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    • 2019-01-09
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    相关资源
    最近更新 更多