Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: running a thread in background

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

like image 471
Gerardo Avatar asked Sep 24 '26 07:09

Gerardo


2 Answers

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.

like image 60
CommonsWare Avatar answered Sep 25 '26 20:09

CommonsWare


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.

like image 22
user275479 Avatar answered Sep 25 '26 20:09

user275479



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!