Kai Zhao Kai Zhao - 2 months ago 25
Android Question

difference between asyntask and service in android

I am a beginner of Android Programming, and when I learn something about Service ,the problem has become.
We all know that the UI thread cannot run a long-time process, so we should run them in a new thread, and immediately ,we have recognised that something about Handler AsyncTask and Service even send a BroadCast when the task has been finished.However, I am not sure when to use them.

For example, we often using an activity to login, when the data should be posted, maybe post to the remote server, it may cost a long-time,we cannot write something in LoginActivity maybe in an AsyncTask or a Service to do that.But which is the better choice ?


As a general rule:

  • A service is running in background and does some (periodic) work for you. For example if you want to fetch news from a REST-API every 15 minutes and informed the user within the app or with a notification than use a service.
  • An AsyncTask is an separated thread for work intensive jobs to prevent the UI thread from blocking. For example fetch the news after the user clicks the "Get News" button.

In your case, the expectation of the user is important. The user tries to login and waits in an activity for the responds of the server. You should send the request to the server in an AsyncTask and e.g. show the user a waitscreen until the response is there ("Try to login"). So the UI is still responsive but the user clearly knows, that he has to wait for a response.