0

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.

4

1 回答 1

1

onStartCommand 总是在主线程上调用。如果你想在另一个线程上运行代码,你必须在你的服务中创建它。默认情况下,服务不创建线程(例外:IntentService 将创建线程,并从该线程调用 onHandleIntent)。

一次只存在一个服务实例。再次启动它不会创建新的 Service 对象,但它会以新的意图再次调用 onStartCommand。如果您不希望创建两个线程,您必须自己阻止它。通常通过保持对线程的引用并且如果不为空则不创建它。

于 2019-07-06T08:20:43.630 回答