每1分钟后台工作,服务,我应该叫`stopSelf()`?

时间:2016-09-07 06:58:48

标签: android android-service alarmmanager android-pendingintent

我使用AlarmManager每1分钟启动一次服务以执行一些后台工作。

以下是代码段:

    Intent intent = new Intent(context, PostLocationService.class);
    PendingIntent pendingIntent = PendingIntent.getService(context, POST_LOCATION_REQUEST_CODE, intent, 0);

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    alarmManager.setInexactRepeating(
            AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + TEN_SECONDS_INTERVAL,
            ONE_MINUTE_INTERVAL, pendingIntent);

PostLocationService延伸Service。在onStartCommand()我做了一些工作,并在完成这项工作后致电stopSelf()

但我知道如果此服务仍在运行,下次接收意图onStartCommand()将再次执行,并且需要完成工作。

这里的最佳做法是:每1分钟启动一次新服务还是保持一项服务正在运行并等待意图?

1 个答案:

答案 0 :(得分:0)

利用IntentService进行快速后台任务。

  

IntentService是服务的基类,可根据需要处理异步请求(表示为Intents)。客户端通过startService(Intent)调用发送请求;服务根据需要启动,使用工作线程依次处理每个Intent,并在工作失败时自行停止。

相关问题