停止AsyncTask的片段中,当后退按钮pressed [英] Stop AsyncTask in Fragments when Back Button is pressed

查看:154
本文介绍了停止AsyncTask的片段中,当后退按钮pressed的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个活动,该主机的片段。 pressing一个按钮,通过FragmentTransaction从碎片A去B片段和添加到后退堆栈。现在B片段具有从SD卡加载图像和图像加载它发布一个AsyncTask的实现。如果我preSS后退按钮,我的应用程序崩溃。 。错误报告表明,异步任务是问题,因为它仍然加载时后退按钮是pressed,所以我的问题是,我怎么能和我应该在哪里停止的AsyncTask时后退按钮已被pressed返回到previous片段/活动?..谢谢你。

i have an activities that host fragments. pressing a button goes from fragment A to fragment B through a FragmentTransaction and the added to the back stack. Now fragment B has an AsyncTask implementation which loads images from an sdcard and publishes it as an image is loaded. if i press the Back button, my app crashes. . The error report indicates that the async task is the problem as it was still loading when the Back button was pressed, so my question is, how can i or where should i stop the AsyncTask when the Back button has been pressed to return to the previous fragment/activity?.. Thank you.

推荐答案

覆盖您片段的onStop()和做的:

Override the onStop() of your fragment and do:

protected void onStop() {
    super.onStop();

    //check the state of the task
    if(task != null && task.getStatus() == Status.RUNNING)
        task.cancel(true);
}

这篇关于停止AsyncTask的片段中,当后退按钮pressed的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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