So, I’m streaming music in a separate thread. If I leave the app (onPause(), onStop() getting called, etc), the music continues to play, but eventually — after opening other apps and switching between them and going back to the home screen — my app is killed. No crash, just a WIN DEATH and process com.myapp.android has died in logcat. Obviously, it’s legit for apps to be destroyed by the system in order to reclaim resources.
My question is: does running stuff in a thread off of the main (UI) thread mean that it now has less priority as far as the system is concerned? Meaning, is it more likely to be killed than if I run the media player in a Service and even use startForeground() to make the service run in the foreground?
Any thoughts or clarification would be greatly appreciated!
EDIT
Also, part of the documentation on Services confuses me. In pertinent part, it states:
Caution: A service runs in the main thread of its hosting process—the
service does not create its own thread and does not run in a
separate process (unless you specify otherwise). This means that, if
your service is going to do any CPU intensive work or blocking
operations (such as MP3 playback or networking), you should create a
new thread within the service to do that work.
I’ve always ran MP3 playback in a service on the main thread and the UI remained responsive. If I’m supposed to put it in a separate thread as recommended in the above quotation, then won’t I end up back where I started, namely with the media playback occuring off of the main thread, thereby increasing the likelihood that the playback is killed when other apps are opened, etc?
I think most of your question is answered in the Android documentation on Services.
From the link:
To answer your question, yes, running a separate
Threadoff of anActivityis going to have lower priority than aServicerunning in the foreground, if theActivitythat started theThreadhas been stopped/paused.Personally, I would recommend doing this in a
Service, as this is exactly the sort of thing theServiceclass has been created for.Edit:
Interesting, what you suggest seems contrary to what I have read (everything is responsive when not using thread in
Service). Regardless, it probably should be started in a background thread.The thread (a thread that YOU create) won’t die unless the process dies, and that will happen when the runtime decides that resources are needed.
Activity‘s can be killed when they are not in the foreground, so theirThread‘s can be destroyed too. If you have aServicemarked as foreground, it is less likely to be destroyed, and therefore, you should not have the same problem.