androidperformanceandroid-serviceandroid-thread

Trying to start already running service in background thread


I want to start a Service for a long running location fetching task. I've chosen to use a foreground service for this task. I want this service to run in the background thread.

Now, after searching a bit, I have decided to start a new thread in onStart() of the Service and not the Activity itself. I don't want any memory leaks with the Thread having reference of Activity. I am fine with Activity being destroyed.

My question is, on which Thread is onStartCommand() is called? What will happen when I try to start the Service again?

I am not very experienced when it comes to threading, please point out anything I'm missing or am wrong about.


Solution

  • onStartCommand is always called on the main thread. If you want to run code on another thread, you must create it in your Service. Services by default do not create a Thread (exception: an IntentService will create a thread, and call onHandleIntent from that thread).

    Only one instance of a Service exists at a time. Starting it again will not create a new Service object, but it will call onStartCommand again with the new intent. If you do not wish two threads to be created, you must prevent it yourself. Generally by keeping a reference to the thread and not creating it if not null.