Reputation: 3336
I have an IntentService
and I want for the startCommand
to be called only if it's not already running.
The reason for this is this service is processing all existing rows in database. It can be called to start several times but if it's already running it shouldn't be started again. And similar to IntentService
after there are no rows to be processed, it should close itself.
Is this achievable? Maybe with PendingIntent
and FLAG_NO_CREATE
?
I could create this with a Service
and a separate thread instead of a IntentService
but IntentService
already has the thread implemented.
Upvotes: 0
Views: 422
Reputation: 1007359
Maybe with PendingIntent and FLAG_NO_CREATE ?
That flag refers to creating the PendingIntent
, not the service.
Is this achievable?
Off the cuff:
Step #1: In your service, add an AtomicBoolean
field (here called isRunning
), initially set to false
.
Step #2: Override onStartCommand()
. If isRunning
is false
, set it to true
and chain to super.onStartCommand()
to inherit normal IntentService
behavior. If isRunning
is true
, do not chain to super.onStartCommand()
.
Step #3: In onHandleIntent()
, wrap all your work in a try
/finally
block, where you set isRunning
to false
in finally
.
Net: a startService()
invocation will only go through normal IntentService
processing if onHandleIntent()
is not already running.
Upvotes: 1