Application threads vs Service threads

2019-01-08 21:55发布

问题:

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.

回答1:

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.



回答2:

From my experience (1+ years developing Android), there is no difference between running a new thread in a service or in an activity. Try not to keep a reference to the Activity in the new thread - use the application context.

Also, the service's life-cycle didn't help at all because some methods are not guaranteed to be invoked :(

The only difference may be that the service can be destroyed without destroying the app completely - thus potentially destroying the new threads. Why potentially? because on the practical side, this doesn't happen. The app ALWAYS gets killed without killing the service before that, meaning: the local service mechanism is useless!!!

Remote service is a different discussion - I was referring only to "where should I run a new thread?".

Good luck!!!