Reputation: 139
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?
Upvotes: 1
Views: 1617
Reputation: 64700
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
.
Upvotes: 1