0

I use AlarmManager to start service every 1 minute to perform some background job.

Here is code snippet:

    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 extends Service. In onStartCommand() I do some job and call stopSelf() after this job is done.

But I know that if this service is still running, next time on receiving intent onStartCommand() will be executed again and needed job will be done.

What is the best practice here: start new service every 1 minute or keep one service running and waiting for intents?

Burhanuddin Rashid
  • 5,260
  • 6
  • 34
  • 51

1 Answers1

0

Make Use of IntentService for quick background tasks.

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

n.arrow001
  • 1,090
  • 3
  • 10
  • 28