Reputation: 3433
In the app I am working on, I have an AlarmManager
that starts a Service
at specified times and intervals. The Service
uses some data I send in the Intent
to read/write the SQLite database, make a Notification
and send an SMS. I've had a problem that when the device goes into "deep sleep" and I use the device again, I get a force close with a NullPointerException
on the Intent
in the Service
. As I've done some research, I've had several questions about how a Service
works that I haven't been able to answer:
1) I realized that I was using the deprecated onStart
method for a Service
. I am going to switch to onStartCommand
with START_REDELIVER_INTENT
flag (think this was the null exception I was getting because the Service
was trying to restart with the old onStart
and not getting the original Intent
). My question is this: Should I put the work the Service
does in the onStartCommand
or in onCreate
? Is there any functional difference?
2) Considering what I am doing in my Service
, is this enough work to put in its own Thread
?
3) Do I need to specifically call stopSelf
? If so, where is the best place to call it?
4) This one is more ambiguous: To my knowledge, I had canceled all of the alarms registered and after deep sleep, I still got the null exception for a Service
. Is there any reason the Service
would still get run even though I never triggered it with an alarm?
Please ask any clarifying question if necessary. I haven't posted code because most of it is generic for starting and consuming a Service
, but if you want to have a peek, let me know. Thanks.
Upvotes: 1
Views: 195
Reputation: 13060
You should use IntentService
instead of regular old Service. It does all its work in a background thread and stops itself automatically when it runs out of work.
Upvotes: 2