tags:

views:

47

answers:

2

I'm trying to write a Service which sits and waits for SMS messages (using a BroadcastReceiver which the server registers) and will take some action depending on the details of the SMS message. I use an Activity to startService() and stopService() for the Service. After I close the Activity, the Service continues to sit there with its state kept and its BroadcastReceiver waiting, as it should... However, I find that over time, randomly, the Service will restart itself. That is, onCreate() and onStartCommand() will be called even when the Service has already been started. This happens sometimes when my phone sits idle overnight...

Can anyone provide insight on why this is (phone requests resources and kills a service?), what I can do to prevent it, or what I can do to prevent the state of the service from being lost?

Thanks in advance.

A: 

I don't think you need to start service from activity at all. Have a broadcast receiver that listens to your SMS messages and starts the service. After work is done, service should call stopSelf();

Alex Volovoy
Should the Activity just register/unregister the BroadcastReceiver? What happens to the BroadcastReceiver once the Activity dies?
jkiv
You define your receiver in the manifest along with actions that it's suppose to listen too. More info herehttp://developer.android.com/reference/android/content/BroadcastReceiver.html and here http://developer.android.com/guide/appendix/faq/commontasks.html#broadcastreceivers
Alex Volovoy
Regardless of the Activity-BroadcastReceiver-Service relationship, onCreate() and onStartCommand() are being called when the Service is doing its work. What's odd is, the state of the Service is reported as it would be if one started the Service fresh. However, upon receiving an SMS, I can have the Service report its state and its state is showing as it should be if it was doing work. This leads me to think that a second instance of the Service is being created?
jkiv
Android is probably killing the service and it's creating itself again. That's normal behavior
Falmarri
My service uses Handler to schedule repeated tasks. If the Service is being killed randomly, should I use AlarmManager instead?
jkiv
A: 

I'll try Service.startForeground()

jkiv
This stopped the Service from being killed. However, any Handler's I was using don't work after extended periods of time.
jkiv