Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

android - What to do with AsyncTask in onPause()?

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

public class MyActivity {
    private AsyncTask mTask;

    private void doSomethingCool() {
        mTask = new AsyncTask(...);
        mTask.execute();
    }

    @Override
    protected void onPause() { 
        super.onPause();

        // How do I let the task keep running if just rotating?
        if (isFinishing() == false) {
            ... 
        }
    }
}

So if the user is rotating the device, onPause() will get called, but I don't want to cancel the task just because of that. I know there's a way to tell the system to not actually destroy my activity on rotation, but is that recommended for this problem? Should I instead put the AsyncTask in a static global class that won't be bound to the Activity?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...