Jesse Luke Orange
Jesse Luke Orange

Reputation: 1999

Performing Network Operations in Android without the use of AsyncTask

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

Answers (3)

Prem
Prem

Reputation: 4831

Network operations in Android can be done in any of the following ways.

  1. Async Task
  2. Intent Service
  3. WakefulBroadcastReceiver or CommonsWare's WakefulIntentService

When should i use each of this option ?

  1. Work should be done in ~1 second or less - Async Task
  2. Work may take more than 1 second but less than 10 seconds - IntentService
  3. Work may take more than 15 seconds - WakefulBroadcastReceiver

Upvotes: 1

codeMagic
codeMagic

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).

AsyncTask Docs

Upvotes: 1

nKn
nKn

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 Threads? 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

Related Questions