多次执行 AsyncTask [英] Execute AsyncTask several times

查看:34
本文介绍了多次执行 AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的活动中,我使用一个从 AsyncTask 扩展的类和一个作为该 AsyncTask 实例的参数.当我调用 mInstanceOfAT.execute("") 时,一切都很好.但是当我按下再次调用 AsyncTask 的更新按钮时应用程序崩溃(如果网络作业不起作用).原因然后出现一个异常,上面写着

In my Activity I use a class which extends from AsyncTask and a parameter which is an instance of that AsyncTask. When I call mInstanceOfAT.execute("") everything is fine. But the app crash when I press an update button which calls again the AsyncTask(In case the network job didnt work). Cause then appears an Exception which says

无法执行任务:任务有已经被执行(一个任务可以只执行一次)

Cannot execute task: the task has already been executed (a task can be executed only once)

我尝试为 Asyctask 的实例调用 cancel(true),但它也不起作用.迄今为止唯一的解决方案是创建 Asyntask 的新实例.这是正确的方法吗?

I have tried calling cancel(true) for the instance of the Asyctask, but it doesnt work either. The only solution so far it's to create new instances of the Asyntask. Is that the correct way?

谢谢.

推荐答案

AsyncTask 实例只能使用一次.

相反,只需像 new MyAsyncTask().execute("");

来自 AsyncTask API 文档:

From the AsyncTask API docs:

为了让这个类正常工作,必须遵循一些线程规则:

There are a few threading rules that must be followed for this class to work properly:

  • 任务实例必须在 UI 线程上创建.
  • execute(Params...) 必须在 UI 线程上调用.
  • 不要手动调用 onPreExecute()、onPostExecute(Result)、doInBackground(Params...)、onProgressUpdate(Progress...).
  • 任务只能执行一次(如果尝试第二次执行,将抛出异常.)

这篇关于多次执行 AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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