Imagine a chat-room style activity. It has a listview of the most recent chat messages.. Every 5 seconds I pull new messages from the server..
I am trying to find the best way to periodically do the server fetch in the background. I had it working great with ASyncTask in onCreate but then had to decide how to keep making it recurring..
When I start the download from server I display the text "Reloading" on screen, and I clear it when I am done..
I looked at:
1) Having ASyncTask doInBackground() run an infinite while() loop with a 5-second Thread.sleep() and regular publishUpdate but that didn't allow me to turn on and off the "Reloading" text as I need to send a message to the UI thread at the beginning and end of every while loop iteration.
2) I next looked at using a simple Thread.run(), t.start() in my onCreate method with a while loop and usng a Handler to pass the message to/from the UI to display/hide the Reloading text.. This works okay but now my issue is:
How to stop/resume the thread in onPause and onResume?
I had the while() loop in my run() function use a variable - while(runThread) and I set runThread to false in onPause.. but the Thread does not get cleaned up by the OS.. When I come back to onResume and I do t.start(), I throw an exception that the thread is already running...
Any thoughts on how to make this work? Is there a better approach I am missing? Given that I want a simple 5-second server fetch and only while this activity is in the foreground..
Cheers and thanks!