Chang Hyun Park
Chang Hyun Park

Reputation: 531

Android Service Initialization. Should I use threads?

I'm coding a simple Android Service which will do some File IO intensive job. The service will be running in the background for a while, and initializing the service will take a while. (It'll take longer as there are more files to scan).

  1. So I thought that I should use a thread to initialize the service, since services are run on the UI thread. Will this be a good idea?
  2. Should I wait for the initializing thread to end by calling the join() method and execute any more less time consuming jobs?

The reason I'm trying to use threads for initialization is because I don't want my activity starting the service to hang when my service is starting up.

Update Okay, The reason I'm trying to use a service is to provide a means for an external client(such as a web browser, or a PC client) to access the files of my android phone. I also want to allow the service to keep running when my application goes to the background.

Upvotes: 0

Views: 2154

Answers (2)

Khantahr
Khantahr

Reputation: 8528

Take a look at IntentService. It automatically runs in a separate thread and exits when it finishes its work. Seems like it would be appropriate for your situation.

Upvotes: 1

David
David

Reputation: 4817

Do you really need a Service? If your code will do a lot of work in the Service it is always a good idea to do it in a thread. If you do not really need the Service, think of using an AsyncTask.

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. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.

http://developer.android.com/guide/components/services.html

Upvotes: 1

Related Questions