The other day i came across something that i hadn't known before , do you
know that when you flip your android phone and go from portrait mode to landscape or vice versa, whatever application is running will be killed by android and recreated again?
It wouldn't be a problem as long as lifeCycle methods of your activity are implemented well, but what if you have a seperate thread which is working behind the scene and interact with your activity through a Handler, like what I have used in both WhitePage and YahooSearch applications. what happens? if you switch the screen mode while our Thread is working the activity is killed, but our Thread is abviously not notified about what has happend, so it will send the message through the old handler to the old activity which might be waiting for Garbage Collection or whatever else but it is not the activity which you wanted to send your message to.
so I've come up with this solution, I override onSaveInstanceState() method of activity class, it checks whether there is any unfinished task running, if so it locks the thread and save it, we also need to check if there is any saved thread in onCreate() method and unblock it with a new Handler class so that Messages will be delivered through the right Handler.(NOTE : we can also use onRetainNonConfigurationInstance() and getLastNonConfigurationInstance() methods which is apparently a better approach to solve this particular problem. ***Please see comments on this Post*** )
On the other side, in our Thread I added a new flag which is checked just before the thread wants to send a message back, if everything is alright it carries on and send a message, otherwise it will wait until it's notified that it is safe to send a message.
you can also use Android AsyncTask class when you need a background task, which is a neat way to do it (if you will) , but be aware of the fact that it does not support the issue we discussed here by default. so you will still need to somehow handle it by yourself.