Android AsyncTasks如何检查活动是否仍在运行 [英] Android AsyncTasks How to Check If activity is still running

查看:406
本文介绍了Android AsyncTasks如何检查活动是否仍在运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我的应用程序中使用了AsyncTasks,以便延迟下载和更新UI.

I have used AsyncTasks with my application, in order to lazy download and update the UI.

目前,我的AsyncTasks只是简单地更新UI:

For now my AsyncTasks updates the UI real simply:

protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        gender.setText(values[0]);
}

我的问题是如何检查TextView呈现的性别的活动是否仍然可用?

My problem is how to check if the activity which the gender TextView rendered from, is still available?

如果没有,我将得到一个错误,我的应用程序将关闭.

If not, I will get an error and my application will shut down.

推荐答案

您可以在活动的onDestroy中取消异步任务

You can cancel your asynctask in the activity's onDestroy

@Override
protected void onDestroy() {
    asynctask.cancel(true);
    super.onDestroy();
}

并在执行更改时检查您的异步任务是否已取消(活动被破坏)

and when performing changes you check whether your asynctask has been cancelled(activity destroyed) or not

protected void onProgressUpdate(String... values) {
    super.onProgressUpdate(values);
    if(!isCancelled()) {
         gender.setText(values[0]);
    }
}

这篇关于Android AsyncTasks如何检查活动是否仍在运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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