开发者

how to handle locale and asyncTask for an activity in android when orientation changes

I'm now to android. And I'm having trouble in developing application in which I'm supposed to load data from a server and then populate list with this data. I used asyncTask to do so and I used onRetainNonConfigurationInstance() function to handle changing screen orientation while loading the data and it worked well.

The problem started when I wanted to handle changing the locale of my activity. As when I change the orientation the locale changes I've read these:-

How do I save an Android application's state?

and Activity restart on rotation Android

I want to make the layout to change from landscape to portrait So I didn't use

android:configChanges="locale|orientation"

I still can't solve it. I think that the system changes the language on its own so when I change the orientation even if i tried to set it using

Locale locale = new Locale("ar"); 
                Locale.setDefault(locale);
                Configuration config = new Configuration();
                config.locale = locale;
                getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());

I'll need to finish the activity and o开发者_开发知识库pen it again which will make the user waits more also it'll make the application crash when the user try to change the orientation again.

I think that I may use onRetainNonConfigurationInstance() but i don't know how with these things I need to handle. So ANY Help will be appreciated.


I am just guessing now but maybe you can use

onSaveInstanceState(Bundle)

and

onRestoreInstanceState(Bundle)

to restore your locale after a configuration change.


Each time configuration is changed, new Resources object is created that points to correct (configuration-dependent) resources. So all your previous changes to Resource object are discarded.

In your case you need to re-set locale each time your onCreate() is called.

As advoce, do not use android:configChanges unless you really understand all the consequences and have strong reasons to use it. Please carefully read Handling Runtime Changes for more details.

And another tip, it might be a good idea to move your AsyncTask to a dedicated service. As services are better adopted for such "background" tasks and handle configuration changes much better, though more code is required. You have to be very careful when using AsyncTasks that should survive configuration changes. I've written two posts about background threads in Activites: part 1 and part 2.


If you're using Fragments, consider putting your AsyncTask in a Fragment that retains itself. Add it with a tag, and you can retrieve it again in onCreate.

I'm struggling to find it now, but I think this is used in Google's I/O app.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜