后台任务碎片和"不能perfom及的onSaveInstanceState后QUOT这个动作; [英] Background tasks fragments and "Can not perfom this action after onSaveInstanceState"

查看:118
本文介绍了后台任务碎片和"不能perfom及的onSaveInstanceState后QUOT这个动作;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个片段以下的AsyncTask(这个例子被简化清楚显示错误):

I have the following AsyncTask in a Fragment (the example is simplified for showing clearly the error):

private class LoginTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {

        // Do network login
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        FragmentActivity act = (FragmentActivity) getActivity();
        if (act != null && isAdded()) {
            act.getSupportFragmentManager().beginTransaction()
                    .add(new LoginDialogFragment(), "loginMessage").commit();
        }
    }

}

有一次,离开而任务正在运行,我收到了 IllegalStateException异常应用程序:无法执行后的onSaveInstanceState这个动作

我想这是因为我的activiy的的onSaveInstanceState和碎片从活动unattachment之间被称为(或因为活动是getActivity()调用和附加片段调用后独立的。

I suppose it is because I called it between the onSaveInstanceState of the activiy and the unattachment of the fragment from the activity (or because the activity was unattached after the getActivity() call and the add-fragment call.

所以,我怎么能在将来避免这个错误?谢谢!

So how can I avoid this error in the future? Thanks!

推荐答案

的onPause 的onStop 的onDestroy ,电话 .cancel()的AsyncTask (此可能需要你的的AsyncTask 为您的活动的一个成员变量)。然后,在你的 onPostExecute()方法,检查过程中被取消了。

In onPause, onStop, or onDestroy, call .cancel() on the AsyncTask (this may require that your AsyncTask is a member variable in your activity). Then, in your onPostExecute() method, check if the process was cancelled.

protected void onPostExecute(Void result) {
    if (!isCancelled()) { // Do stuff only if not cancelled
        FragmentActivity act = (FragmentActivity) getActivity();
        if (act != null && isAdded()) {
            act.getSupportFragmentManager().beginTransaction()
                    .add(new LoginDialogFragment(), "loginMessage").commit();
        }
    }
    return null;
}

注意:您可能还需要检查 isCancelled()你的有任何环doInBackground()等等不要将你做的东西一旦该人已离开该应用程序。

NB: You may want to also check isCancelled() in any loop you have in doInBackground() so you don't keep doing stuff once the person has left the app.

这篇关于后台任务碎片和&QUOT;不能perfom及的onSaveInstanceState后QUOT这个动作;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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