What to do with AsyncTask in onPause()?

后端 未结 4 2007
无人共我
无人共我 2020-12-09 13:07

I\'m using an AsyncTask in my activity. Looks like:

public class MyActivity {
    private AsyncTask mTask;

    private void doSomethingCool() {
        mTas         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 13:48

    This adds onto Daniel's answer, but is more characters than I can fit in a comment.

    More often than not, when I'm using an AsyncTask, I want a dialog spinning, and dealing with that is absurd. You have to do something very much like the solution in the thread that Daniel links to.

    The basic principle is, have the Task object keep an explicit reference to its parent. Hold onto the Task object across screen rotations, (using onRetainNonConfigurationInstance), and then in onCreate, make sure that if the Task exists and you're coming from a screen rotation, set the Task's parent activity to the new instance. Inside the task, make sure to call all Activity methods on the explicit parent.

    You can see an example of me doing this on a basic ListActivity here: http://github.com/klondike/android-campfire/blob/master/src/com/github/klondike/android/campfire/RoomList.java

    One thing I'd do differently than in that example, is that I'd move as much of the Task's onPostExecute into a method on the Activity, just for code cleanliness reasons.

提交回复
热议问题