Handle screen orientation changes when there are AsyncTasks running

后端 未结 3 1542
庸人自扰
庸人自扰 2020-12-01 02:15

I\'ve been bugged by this for a while. How do I properly handle screen orientation changes while I have a separate Thread / AsyncTask running? Curr

相关标签:
3条回答
  • 2020-12-01 02:48

    I already popped up similar question here.

    Basically there is an example of how to pause/resume an AsynTask on device rotation. However it still does not fit for all cases (sometimes it is not possible to safely suspend the action, such as a new user creation on a remote server). For those "unsafe" cases you need to code somewhat I'd call a tricky "framework". You will see CommonsWare gives github links to the one.

    0 讨论(0)
  • 2020-12-01 02:49

    Take a look the droid-fu library BetterAsyncTask. It is meant to handle this exact case.

    http://brainflush.wordpress.com/2009/11/16/introducing-droid-fu-for-android-betteractivity-betterservice-and-betterasynctask/

    0 讨论(0)
  • 2020-12-01 02:51

    I had a similar problem to your and worked around it by implementing the AsyncTask as part of a class which inherits from Application class. An Application class is available all the life time of the application So you don't have to worry about your AsyncTask getting interrupted unless the whole application will be killed.

    To get notified when the task has finished the Activity has to implement a interface which it uses to register itself to the Application class.

    When your application is destroyed because of the screen rotation you can unregister your Activity from the Application class and re-register it when it is recreated. If the task finishes between destruction and recreation the result of the operation can be stored in the Application class meanwhile so the Activity can check whether the task is still running or whether the result is already available when it is recreated.

    Another advantage is that you have direct access to the applications context because the Application class is a sub class of the Context class.

    0 讨论(0)
提交回复
热议问题