views:

619

answers:

2

Hi, is there any way to leave a thread in background when i close the app in android? I read about a Service but implementing it is too much than i need. Thanks

+8  A: 

Hi, is there any way to leave a thread in background when i close the app in android?

That will happen by default. That does not mean it is a good idea.

I read about a Service but implementing it is too much than i need.

More likely, it is precisely what you need.

If you start a thread in an Activity, then fail to stop that thread, it will run forever, until Android terminates the process, since you have no way of stopping it. The only sort-of acceptable exception is if your thread stops itself, and then you have to be very very careful that it actually does terminate cleanly. On the other hand, you can arrange to stop a running Service whenever you need, from any Activity, and that Service can arrange to stop the thread, so you don't leak the thread indefinitely.

I strongly encourage you to implement a service that manages the thread.

CommonsWare
I think he probably meant that a Service is much more complex to implement (and it is). I agree that that's probably the right tool for the job though.
fiXedd
Whilst creating a Service is more complex than starting a thread, I was surprised at how easy it really was. http://www.brighthub.com/mobile/google-android/articles/34861.aspx provides a good introduction
dparnas
thanks everyone. i'll try to implement a service instead of a thread
xger86x
thanks for this commons - actually reading your book now and I came to SO to find the answer to this exact question aka "why use a local Service instead of just a thread inside the Activity." I will still look for more reasons, but this is definitely a great one!
Hamy
+2  A: 

Another reason to use a Service is that the platform will give the process priority to NOT be killed while it is in the background.

it's that i need.. so i use a Service. thanks
xger86x