'Stop Thread in background

Can any body please help me out? My problem is I have a thread(TCP socket) class in android which starts when android app login but I want to stop thread when application is in background, please let me know how can I do it? because it is consuming huge cpu performance and ram also hanging my device.



Solution 1:[1]

Base on my experience, you can set the timeout to a very short number, and close the Socket if your app goes to background.

Let me explain more...

  1. register a permission to receive the event of app-goes-to-background
  2. start a new Socket with very short timeout setting.
  3. when you received the event of app-goes-to-background, mark a global flag
  4. while waiting for new message from remote server that connected by the Socket, a exception will be trigger when timed-out. During this situation, check the abovementioned global flag. If the flag shows your are in app-goes-to-background status, close the socket (and maybe trigger another thread to check the status of the global flag, so that you can start a new Socket). If the flag shows you are NOT in the background, just keep receiving new message from remote server (and wait for next timeout).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1