开发者

Android progress bar not updating after screen orientation changed

While developing an android application I have constructed an activity that contains a progress bar. There is an async task that will update the progress bar in an activity. After the screen orientation changed, The progress bar not longer get updated while the async task still in progress. I believe the 开发者_如何学运维async task is not referencing to the new progress bar instance that was created when android invoke onCreate method after screen orientation changed.

Appreciate if anyone can show me any tip for this.

Thanks.


Your correct you AsyncTask doesn't know the new instance of the activity as the activity was destroyed and recreated during the orientation change.

But there's a method which gets called when the orientation changes and which you can use to pass the AsyncTask to the new activity.

onRetainNonConfigurationInstance() gets called before the activity gets destroyed, override the method and return a reference of your running AsyncTask. Within the onCreate() method you can then retrieve the AsyncTask due to a call to getLastNonConfigurationInstance(). Be aware that you have to handle the cases where you activity is created the first time and getLastNonConfigurationInstance() will return null.

Furthermore you have to pass your activity to the AsyncTask so it can reference the progressbar od the current activity. Therefore I suggest to implement two method to register and unregister an activity to/from the AsyncTask. So in onRetainNonConfigurationInstance() you unregister the "old" activity which will get destroyed and in onCreate you either register the newly created activity to a new AsyncTask or to the one you retrieve from getLastNonConfigurationInstance().


I know this is old, and things might have changed, but Flo's answer should not be the accepted one. Per the documentation here: onRetainNonConfigurationInstance ()

"This function is called purely as an optimization, and you must not rely on it being called."

In other words, if you are doing something important, and that 'thing' MUST happen when an activity is destroyed, this is a bad solution.

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


From the asynctask maybe instead of directly referencing the ProgressBar, you could update the progressbar within a method of the activity. eg.

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

in the activity:

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

You can save the state of the activity before it is destroyed by overriding onSaveInstanceState(). Save the progress integer in here and then in onCreate, check if savedInstanceState is not null then create the progress bar set at the saved integer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜