Android progress indicator does not update after changing screen orientation

When developing an Android application, I created an operation containing a progress bar. There is an asynchronous task that will update the progress bar in action. After changing the screen orientation, the progress bar is no longer updated while the asynchronous task is still running. I believe that the async task does not reference the new instance of the execution line that was created when android calls the onCreate method after changing the screen orientation.

Please rate if anyone can show me any advice for this.

Thanks.

+4
source share
3 answers

Your correct AsyncTask address does not know the new instance of the activity, because the activity was destroyed and recreated during the orientation change.

But there is a method that is called when the orientation changes and which you can use to pass AsyncTask to the new action.

onRetainNonConfigurationInstance () is called before the action is destroyed, override the method and return the link to your running AsyncTask. Inside the onCreate () method, you can get AsyncTask due to the call to getLastNonConfigurationInstance () . Keep in mind that you should handle cases when your activity is created for the first time, and getLastNonConfigurationInstance () returns null.

In addition, you must transfer your activity to AsyncTask so that it can reference the progress bar of the current activity. Therefore, I propose implementing two methods for registering and unregistering activity to / from AsyncTask. Thus, in onRetainNonConfigurationInstance () you unregister the β€œold” activity that will be destroyed, and in onCreate you either register the newly created activity with the new AsyncTask, or the one you retrieve from getLastNonConfigurationInstance ().

+4
source

I know this is old and everything could have changed, but Flo's answer should not be recognized. According to the documentation here: onRetainNonConfigurationInstance ()

"This function is called pure optimization, and you should not rely on its call."

In other words, if you are doing something important, and this β€œthing” MUST happen when the action is destroyed, this is a bad decision.

A better solution would be to use onSaveInstanceState(Bundle outState) found here: onSaveInstanceState (Bundle outState)

+1
source

From asintact, perhaps instead of directly linking to the ProgressBar, you can update the progress panel as part of the activity method. eg.

 onPublishProgress(int progress) { updateProgressBar(progress); } 

In action:

 updateProgressBar(int progress) { progressBar.setProgress(progress); } 

You can save the state of an activity until it is destroyed by overriding onSaveInstanceState (). Save the progress integer here and then on onCreate, check if savedInstanceState is invalid, then create a progress bar specified in the saved integer.

0
source

All Articles