Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep AsyncTask during rotation but not on Activity removal

Tags:

android

I have an Activity that runs a simple AsyncTask. To keep the AsyncTask running during screen rotations I am using onRetaingNonConfigurationInstance() to pass the AsyncTask to the new Activity as recommended in one of the answers from the thread How to handle an AsyncTask during Screen Rotation? Then I update a pointer to the Activity in the AsyncTask to make sure it can still update the progress dialog from on onProgressUpdate().

My problem is that using this method I cannot detect if the Activity is only rotated (In this case I want to continue to run the AsyncTask) or if the Activity is hidden by the Home button in which case I'd like to stop the AsyncTask. I can however detect the usage of the back button because in this case the isFinishing() of the Activity returns true;

Is there any mechanism I could use to differentiate rotation versus home button usage?

like image 948
jmbouffard Avatar asked Apr 26 '11 14:04

jmbouffard


1 Answers

If you press the home button the method onRetaingNonConfigurationInstance() shouldn't be called. So you can use some boolean variable which you set in onRetaingNonConfigurationInstance() to true. In onDestroy() you can then check the variable and stop the AsyncTask when it is still false.

Update

I thought about my solution again and after some searching I think it is wrong, as onDestroy() won't be called if you press the home button. And onStop() is called before onRetaingNonConfigurationInstance() so stopping the AsyncTask there will be to early as you don't know if it is a configuration change or not.

An ugly work around would be to call a method on you AsyncTask in oStop() which initialize some sort of self destruction on the AsynTask which you can then stop again in onRetaingNonConfigurationInstance() if it is a configuration change. As I said it is not very elegant.

like image 78
Flo Avatar answered Sep 24 '22 02:09

Flo