开发者

Android , exiting / pausing application, how to destroy thread

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 star开发者_运维问答ting 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜