I have an android application with a background thread that contains a socket connection for sending/receiving data from a server.
If my application ends (back button, etc) or is paused (Home button, calling other app), what is the best way of dealing with this background thread?
I have seen 2 ways:
Call Thread.setDaemon(true)
after creation and before starting the thread
Override onStop()
, onPause()
, or onDestroy()
I just want to ensure that my application doesn't hang or have other strange behavior.
edit:
Also, what's the best solution to close the socket? Do I close it and the inputStream as well? Is that enough?
I'd suggest using a signal variable of some sort: doing something like
public void run(){
while(!stopped){
// do work
}
// clean up
return;
}
And then in onStop()
or onDestroy()
set stopped to true. You'll need to make sure you clean up behind yourself as well, and if you need to re-start the thread you do so in onResume
or onCreate
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.