Thread or services

0 votes
asked Aug 19, 2010 by thanh-le

I'm confused between thread and service on android. If I have to download some file from the server. It may be multiple files at a time. What should I choose in this situation, thread or services?

5 Answers

0 votes
answered Aug 19, 2010 by jacknad

Thread is fine for doing a task in background for one application. You would want to use a service if you needed this for multiple applications.

0 votes
answered Aug 19, 2010 by alopix

If you want to provide an interface for other Apps to communicate with your downloading Activity: service. If the download should just run in the background to allow the user to interact with the UI.

0 votes
answered Aug 19, 2010 by janusz

Doing Stuff in a Service does not make it run in the background. You have to create a Thread in your service as well to wait for the download to complete.

If you are using a thread that is local to an activity you will have problems with leaving the activity, sending it to the background or an interruption because of an incoming call etc. This may cause your app to be killed by the OS to free up memory. In this case your thread is lost and may not get restarted and make your app crash.

If you create a service you are not as likely to be killed then just a thread and you can specify the OS to restart the service after it gets killed by the OS. This makes the service a more secure choice for very long downloads. I use a service in one of my apps to download a 20 mb file and in this service create a thread that does the downloading.

A service only helps you to encapsulate the download and decouples it from the activity and gives you another state in the OS that will prevent the thread from just disappear because of low memory.

0 votes
answered Aug 19, 2010 by commonsware

What i should choose in this situation thread or services?

It's not an "or". It's an "and". You use a background thread and a service.

A service is "in the background" from a UI standpoint, in that it has no UI. A service is not automatically "in the background" from a threading standpoint, in that onCreate(), onDestroy(), onStart(), and onBind() are all called on the main application thread, the same thread shared by all the activities of this application. Anything long-running, like a download, needs to be done outside of the main application thread, such as using an AsyncTask.

If your downloads need to go on even if the activity that triggered them is destroyed, you need to use a service, with the service using an AsyncTask or background thread to complete the download. Even better is to use an IntentService, which combines a regular service with a background thread.

0 votes
answered Aug 15, 2011 by dev-mz

your question is already in the documentation. Check the right column.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...