Reputation: 14044
I am working on a service, which extends the Service class and using a seperate thread to handle incoming messages, so, I have the following in my onCreate method
thread = new HandlerThread("MYSERVICE-THREAD",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
serviceLooper = thread.getLooper();
serviceHandler = new ServiceHandler(mServiceLooper);
In this thread, I create a LocationManager and sets it up to listen for location changes. I'm slightly worried about the lifecycle of the thread though. This is why:
If I don't remove the location listeners from the location manager in the onDestroy method of the service, and force a location update via telnet, everything works fine. I found this strange and tried explicitly ending the thread with thread.quit() in onDestroy method of the service. So, now when doing a location update from telnet, I get the warning I was kind of expecting in the first place. That a handler was calling a handler on a dead thread.
removing the location listeners from the location manager obviously solves this, BUT, this seems to hint to me that if I dont explicitly close the thread, the thread will continue to run after the service is destroyed. Is this correct? In the examples on developer.android.com they dont explicitly close their thread, so I thought the VM would take care of it in this case.
Upvotes: 2
Views: 1611
Reputation: 36035
Oh yes. This is the case. The same goes for Activities too. Threads stay open until Android explicitly kills them to free up resources unless you close them yourself. In a technical sense, Activities and Services are never closed when popped from the stack. It just tells the OS that all the resources that they were using can now be reclaimed when it's needed so that memory pool will be the first place the OS looks. If a thread of any kind is still running however, it will continue to run (and take up CPU resources) until the memory is reclaimed which could be anywhere between 1 second and eternity.
Upvotes: 3
Reputation: 1006539
this seems to hint to me that if I dont explicitly close the thread, the thread will continue to run after the service is destroyed. Is this correct?
Absolutely. If you fork the thread, you have to clean it up.
so I thought the VM would take care of it in this case.
Well, it will, eventually, insofar as the OS will eventually terminate the whole process for your app. That being said, you do not want to leak threads, and you really do not want to leak a requestLocationUpdates()
call (or whatever it is that you are using with LocationManager
), as that can keep the location provider powered on (e.g., GPS).
In the examples on developer.android.com they dont explicitly close their thread
Which examples are you referring to?
Upvotes: 2