Reputation: 1999
My question is a simple one, I'm looking for advice or links to a useful tutorial on multithreading and networking in Android. Every example I have looked at uses AsyncTask. What I want to know is can you get and use data just with threads and handlers?
I'm aware that the HTTP Request has to be done on a new thread otherwise you get NetworkOnMainThreadException but the reason I want to use threads and handlers is because i want the UI to be updated with said data from the other thread.
I'm not after code really, just pointing in the right direction.
Upvotes: 1
Views: 1062
Reputation: 4831
Network operations in Android can be done in any of the following ways.
When should i use each of this option ?
Upvotes: 1
Reputation: 44571
What I want to know is can you get and use data just with threads and handlers?
Yes. The network operations just have to be done on a background Thread
whether it be using doInBackground()
of AsyncTask
or creating a new Thread
. Look at Painless Threading and Processes and Threads
i want the UI to be updated with said data from the other thread.
No matter what you use, you still have to update the UI
on the main Thread
. This can be done very easily with AsyncTask
using any of its other methods besides doInBackground()
(onPreExecute()
, onProgressUpdate()
, onPostExecute()
all run on the main Thread
).
Upvotes: 1
Reputation: 13761
Think that Threads
are the same as a regular code, with the difference that they're run in background. So the question you have to ask yourself is: Can I use Handlers
if I wasn't running Thread
s? The answer is yes, you would just need to pass the Handler objects between the involved Activities
, Threads
, etc.
Now, if you want advices about what to choose. Keep in mind that AsyncTask
is in fact an "improved" thread, but contrary to popular believings, it's not intended for very long running processes. For instance, if you want to have a thread running all your app life long, this is not the correct election. It's intended for tasks which have an end.
If you want to run long tasks, use a Service
. It's a bit more confusing at the beggining, but that's the correct election. But be careful, a Service
is not a thread! You might however put Threads inside it and treat them as they were running anywhere else.
Upvotes: 0