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 hidd开发者_C百科en 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?
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.
Here I found a very elegant solution how to use AsyncTasks with ProgressDialogs. I cannot say now if it serves your case. Try it.
You have to add this to the activity declaration in the manifest:
android:configChanges="keyboardHidden|orientation|screenSize"
That should keep all your activity unchanged when rotating.
Hope it help
精彩评论