views:

237

answers:

1

What are the advantages/disadvantages in placing a lengthy network access code in a thread in an activity or a thread in a service? How would it affect the application? I am writing a streaming audio player and from what I've read so far putting the code in a service will still end up blocking the application so a new thread is needed, does anyone know if it makes more sense to put this piece of code in a service.

Thanks

+5  A: 

Yes, a blocking operation in a Service will still block the application. Despite first appearances, Services are not simply for running tasks in the background. They are for running tasks with a lifecycle that is independent of the Activity lifecycle (IE, they may continue after the Activity is closed).

A Service that starts when an Activity starts and ends when the Activity ends is useless.

In your case, where you are streaming audio, you may want to stream audio even after the user closes the Activity, in which case, you should use a Service, but you'll still need a thread (or an AsyncTask) for blocking tasks.

synic
Thanks, that's what I thought. On a related topic, at least in the emulator, after I've started the streaming player it would continue to play even after I pressed the back button. I was assuming it would stop when the activity was no longer in the foreground... is it because of the new thread or it will play regardless until android kills the application.
zerayaqob
Yeah, the thread will stay running until Android kills it. If you want it to stop, implement some sort of "active" flag and set it to false in your onDestroy() method.
synic
Also note that threads in an `Activity` are destroyed when the configuration (read: orientation) changes! This is not true for threads in `Service` s.
MrSnowflake
Threads in an Activity won't get destroyed during a configuration change at all. They may, however, have local references to the old Activity, which may be a problem.
synic