做什么用的AsyncTask中的onPause()? [英] What to do with AsyncTask in onPause()?

查看:84
本文介绍了做什么用的AsyncTask中的onPause()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的AsyncTask在我的活动。是这样的:

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) {
            ... 
        }
    }
}

因此​​,如果用户旋转设备,在onPause()将被调用,但我不希望取消的,只是因为该任务。我知道有一种方法来告诉系统实际上没有摧毁我的旋转活动,但该建议在此问题呢?如果我不是把AsyncTask的中不会被绑定到活动一个静态全局类?

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?

感谢

推荐答案

这增加了到丹尼尔的回答,但更多的字符比我能适合评论。

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

很多时候,当我使用的AsyncTask,我想一个对话框纺,和处理这是荒谬的。你必须做一些事情很像丹尼尔链接到该线程的解决方案。

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.

其基本原理是,有任务目标保持明确提及其父。稳守任务对象跨屏幕旋转,(使用onRetainNonConfigurationInstance),然后在的onCreate,确保如果任务存在,你从一个屏幕旋转的到来,设置任务的父活动到新的实例。里面的任务,一定要调用所有的活动方式上明确父。

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.

您可以看到我这样做就到这里基本ListActivity的例子: <一href="http://github.com/klondike/android-campfire/blob/master/src/com/github/klondike/android/campfire/RoomList.java">http://github.com/klondike/android-campfire/blob/master/src/com/github/klondike/android/campfire/RoomList.java

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

有一件事我会做不同于在这个例子中,就是我将尽可能多的任务的onPostExecute成方法的活动,只为code洁净度的原因。

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.

这篇关于做什么用的AsyncTask中的onPause()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆