EGHDK EGHDK - 7 months ago 11
Java Question

Service or Thread or AsyncTask

Pardon my questions, as I'm still very new to programming so I don't fully understand the concepts of mainthreads, and async tasks, and services, and threads. I'm reading the documentation about Services for Android because I want to perform some tasks off the main thread. It says:


If you need to perform work outside your main thread, but only while
the user is interacting with your application, then you should
probably instead create a new thread and not a service.


1.Are they saying that a "thread" stops immediately after you leave the app (i.e: Home button)?


For example, if you want to play some music, but only while your
activity is running, you might create a thread in onCreate(), start
running it in onStart(), then stop it in onStop(). Also consider using
AsyncTask or HandlerThread, instead of the traditional Thread class.
See the Processes and Threading document for more information about
threads.


2.If threads are baked into Java, why does android have AsyncTasks?


Remember that if you do use a service, it still runs in your
application's main thread by default, so you should still create a new
thread within the service if it performs intensive or blocking
operations.


3.Does this basically mean, that almost every service is basically going to have a thread created inside it?

4.Would it be bad to start an AsyncTask inside of a service?

Answer

1.Are they saying that a "thread" stops immediately after you leave the app (i.e: Home button)?

A Thread should be destroyed when the Thread that started it is destroyed. So, if you start a Thread in an Activity then it should be destroyed when that Activity is destroyed or transferred to a Service. For instance, you can start music in a Thread and update the songs there but if you want it to keep playing when the Activity is destroyed then it should be moved to a Service

2.If threads are baked into Java, why does android have AsyncTasks?

An AsyncTask allows you to perform background work and easily update the UI before, during, and after the background work is done by utilizing any of its built-in methods except for doInBackground() because it is the only one that doesn't run on the UI Thread

3.Does this basically mean, that almost every service is basically going to have a thread created inside it?

Not necessarily but you could create a Thread inside of it

4.Would it be bad to start an AsyncTask inside of a service?

No. You could do this.

AsyncTask is a great way to do background work. Its methods make it very easy to update the UI. But you need to read through the documentation carefully (maybe even a few times) to make sure you completely understand how to use them. Also, remember that these are for short-lived operations so they can be good for downloading network data but shouldn't be used for things that last more than a few seconds (According to the docs)