Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Service v/s AsyncTask

I am confused with respect to design of my app. I need to continuously poll a server to get new data from it. I am confused whether Async Task running at fixed interval or Service running is background is better option. The thread will run only when the app is running

like image 556
Ankuj Avatar asked Jan 16 '23 04:01

Ankuj


1 Answers

You have already some answers to your question, but I think it worths a summary ...

What you need

When you want to run a peice of code that takes some time to complete you should always run it in a separate thread from the UI thread.

You can achieve that in 2 ways:

Using Thread:

This is the simplest one, if you don't need a lot of communication from the new thread to the UI thread. If you need the communication, you will probably have to use a Handler to do it.

Using AsyncTask:

Also runs in a separate thread and already implements some communications channels with the UI thread. So this one is preferable if you need this communication back to the UI.

What you don't need

Service

This serves mainly to keep some code running even after you exit the main application, and it will run in the UI thread unless you spawn a new thread using the options described above. You said that your thread are suposed to terminate when you exit application, so this is not what you need.

IntentService

This can be activated by an external event (i.e. BroadcastReceiver) that can start a piece of code defined by you, even if your application is not running. Once again, based on your requirements, this is not what you are looking for.

Regards.

like image 101
Luis Avatar answered Jan 26 '23 06:01

Luis