I am working on an android app to play music.
So far I have returned START_STICKY
from the onStartCommand
of the Service responsible for playing the music without much thought becuase the tooltip in Eclipse states: "This mode makes sense for [...] a service performing background music playback".
The first thing this method does is looking in the intent what it is supposed to do (play, stop, next song, ...).
Recently when I killed the app while playing music (by dragging it out of the screen in the overview of recent apps) the app crashed. Looking in the log file I found that a NullPointerException was thrown when trying to access the intent in onStartCommand
(after the Apllications's and Service's onCreate
methods had been called).
My first reflex was to therefore insert at the beginning of the onStartCommand
method:
if (intent == null){
stopSelf();
return START_NOT_STICKY;
}
But after reading the descriptions of START_STICKY
and START_NOT_STICKY
again I am wondering: Why would START_STICKY
be recommended for a music player?
The way I understand it is that the difference between the two is that if a service started with START_STICKY
is killed it will be restarted (then with intent=null). With START_NOT_STICKY
the service will not be restarted (unless the user requests it), therefore it will always be called with an intent and I would not need to check whether it is null or not.
When the user kills the app it seems obvious to me that the service should not be restarted.
The other case I can think of where the service might be restarted is if the service had been killed by the system due to a lack of ressources. In that case, too, I don't think a user would want the music to unexpectedly start playing music just becuase some ressources became available.
The following two answers imply that the return code has no other meaning than whether the service should be restarted if the process was killed:
- What is START_STICKY,START_NOT_STICKY and START_REDELIVER_INTENT Service
- START_STICKY and START_NOT_STICKY
Why is START_STICKY
recommended for a music player?