开发者

Android AsycTask and orentation changes

开发者 https://www.devze.com 2023-03-18 06:15 出处:网络
How should you handle AsyncTasks when configuration changes occur. I am accessing a ReSTful API through these tasks, and in the cases where I need to get data back and then display it to the user I am

How should you handle AsyncTasks when configuration changes occur. I am accessing a ReSTful API through these tasks, and in the cases where I need to get data back and then display it to the user I am experiencing problems. If a configuration change occurs, like an orientation change then the Activity is not properly update. I believe that the AsyncTask is updating the old activity that has been destroyed. I have found a solution to this that requires creating a boolean in the Application class that keeps track of whether the AsyncTask I car开发者_运维知识库e about is still running, and then on rotations I cancel the listener then recreate it in the new Activity, then when the AsyncTask is done, the listener then displays the data to the user. This works well, but it requires lots of extras and requires a lot of management. Is there a way that the async task can be tied to the new instance of the activity. Or a way to abstract what I have done, so it does not require as much management for each task you have. Thanks


Have a look at asynctask-screen-rotation. This implementation is working quite good for me.


I struggled with that a lot too, the best solution I found was to add android:configChanges="orientation" to your activity in the AndroidManifest.xml file. This will stop your activity from being destroyed and recreated when the orientation changes.

0

精彩评论

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