I have an audio recording app, for which I am currently developing a widget.
Recording is performed by an audio engine running in a service put in the foreground state.
Whenever the audio engine state changes to pause/play/record, a broadcast is sent, and handled by a receiver which updates the widget.
So that clicking on the record button in the widget starts recording, which causes the broadcast to be sent, and in the end the record button to turn red in the widget. Same thing happens if you start recording from within the app instead of the widget.
Everything’s good so far.
Now, if the service gets killed for some reason, onDestroy() is not called and I don’t have a chance to send a pause or shutdown broadcast so that the record button turns off. Result: the button stays red whereas recording has stopped.
This is some of the worst thing that can happen.
Why? The user takes a look at his home screen, he/she sees the red button and thinks recording is still being performed.
It’s not like with music playback, where the user can notice when music stops playing through the headphones… With recording, you don’t hear nothing if it stops.
I can understand the need for the system to kill services. I’m fine with that. I don’t need the service to get restarted and all that.
But I need to update the widget if the service shuts down, so that the user is not misled, thinking that his interview/concert/rehearsal/memo is still being recorded, while it’s not.
So how can I update the widget quickly if the service gets killed?
I have found what I consider to be an answer to my own question.
I return START_STICKY from
onStartCommand() in my service.If I manually kill the service from DDMS, I get this in logcat:
And a few seconds later:
The service does restart, and that allows me to send a broadcast from
onStartCommand()to indicate that the audio engine is paused (I don’t resume recording automatically).The widget provider reacts to this broadcast and updates the widget appropriately.
This works on Froyo and solves my problem: the user is not misled when looking at the widget. Recording stopped because the engine crashed, and the widget reflects this.
It’s not bullet-proof, as it relies on the system restarting the service automatically, but I think that’s quite safe.