AndroidStudent
AndroidStudent

Reputation: 45

Do threads continue to run after service is closed by android?

A service is called on the onCreate in my Main Activity. The service extends from Service class (not IntentService) - in that service, a thread is called, which has an infinite loop - if the thread throws any Exception, it closes the service, and recalls the service (Handled by a try catch block).

Eventually, for any reason, the service is closed by android.

Please answer the following questions:

A) Does my thread continue to run?

.....If so, if a Exception is thrown at any time in the future, will it recall the service?

....If not, will an Exception be thrown to cause the service to start again?

B) Will android just turn of my thread when it turns off my service?

I'm just trying to understand what happens to my application when Android decides to clear my service.

Upvotes: 3

Views: 539

Answers (1)

Vasiliy
Vasiliy

Reputation: 16228

As long as the thread is running it is considered "garbage collection root". Therefore, the thread itself and any other object reachable from that thread will not be garbage collected. If Android framework will not interfere, a thread having infinite loop will continue to run indefinitely. Since your thread can "close" the service, I assume that it has a reference to the service (either implicit or explicit), therefore the entire service will remain in memory.

However, Android do have some means for monitoring apps' memory consumption, and can kill apps in order to free memory. When Android kills an app, it kills the entire process of the app. When the process is killed, all threads are stopped and the memory associated with them is freed, therefore no further activity will take place.

It seems like this is the end of your service, but Android provides additional mechanism to control what happens in that case: you can designate the service as STICKY, and Android will attempt to restart the service as soon as possible. It is discussed in details in this answer.

References:

Most of the information provided in this answer is covered in official Services page and javadoc of service class.

For the more complicated scenario of Service running in a another process there is almost no documentation, but there are many blogs out there. I also wrote a post on the subject: How to establish a reliable (crash and kill tolerant) connection to bound IPC (e.g. AIDL) Service in Android

Upvotes: 2

Related Questions