Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an AsyncTask inside a Service Class?

I have to upload data to a server. I am using a service that is running on the same process as my application. Should I use a Separate thread for upload process or Should I use a AsyncTask to upload data to server ?

More specifically can I use AsyncTask inside a service class ? And should I use it ? This service should always be running in memory in order to send data to the server every 5 seconds.

like image 413
Rakesh Avatar asked Nov 01 '22 04:11

Rakesh


1 Answers

No problem to use AsyncTask in a service.

NOTE / FIX : I was wrong when I said the service runs in background, it only applis to IntentService. As noted in the comments and in the documentation, a service does not create it's own thread :

Caution: A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work.

That means you must use an AsyncTask (or another thread in any case) to perform your upload task.

like image 94
Pierre Rust Avatar answered Nov 10 '22 13:11

Pierre Rust