androidmultithreadingandroid-servicekillandroid-threading

How would a previously started Thread within a Service be stopped if said Service is killed by the system and later restarted?


If a Service implements a thread, it would hold the reference to it using a class field, so that it could later stop the thread by calling the proper methods (e.g. quit() or quitSafely() in the case of HandlerThread) within onDestroy() implementation. My question is, what if the system decides to kill the Service and later restarts it, resulting in class fields being reinstantiated and the reference to the original thread being lost? Since onDestroy() is not guaranteed to be called, how do we make sure previous threads are stopped before creating a new one?

As answers to other related Stack Overflow questions point out, threads are independent from application components' lifecycles. As such, killing of components do not necessarily result in running threads' executions being stopped. Such a situation could result in excess thread creation when components are created and killed repeatedly. What is the best practice for handling such a scenario?


Solution

  • The case where onDestroy() is not called is when the system is destroying your entire process, so at that point, your entire process's memory is dumped and when it comes back, you'll be in a brand new process. There won't be any cleaning up to do from a previous process that is already gone.