【发布时间】:2013-06-26 08:41:21
【问题描述】:
这可能是一个重复的问题,但我没有找到我要找的东西。
我在 UI 活动new LoadData().execute(); 中调用了一个 AsyncTask,在 doInBackground 中我调用了一个需要时间的方法。如果一段时间后数据没有返回,我想中断这个线程。
以下是我尝试执行此操作的代码。
class LoadData extends AsyncTask<String, String, String>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
startTime = System.currentTimeMillis();
}
protected String doInBackground(String... args)
{
DataCollector dc = new DataCollector();
data = dc.collectData(query);
//Here I check if the time is greater than 30 seconds then cancel
if(((System.currentTimeMillis()-startTime)/1000)>30)
{
cancel(true);
}
return null;
}
}
但这并没有在 30 秒后停止任务,实际上它需要更多时间。
我也试过get(long timeout, TimeUnit unit);,但这也不起作用。
谁能告诉我我该怎么做或如何在 doInBackground 中使用 isCancelled()。
谢谢。
【问题讨论】:
-
也许这个答案对你有帮助:stackoverflow.com/a/11191070/3307066.
标签: java android android-asynctask