這可能是一個重複的問題,但我沒有找到我要找的東西。 我在UI活動new LoadData().execute();
和doInBackground中調用一個AsyncTask,我調用一個需要時間的方法。如果數據在一段時間後沒有返回,我想中斷這個線程。 下面是我試圖做到這一點的代碼。一段時間後取消AsyncTask
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()。
謝謝。
也許這個答案可以幫助你:http://stackoverflow.com/a/11191070/3307066。 – jbarrameda