我有一個的AsyncTask如下:如何取消的AsyncTask在Android
private class SearchTask extends AsyncTask<Object, Object, Object> {
@Override
protected void onPreExecute() {
super.onPreExecute();
System.out.println("Start");
}
@Override
protected Object doInBackground(Object... urls) {
SearchFunction();
return null;
}
@Override
protected void onPostExecute(Object result) {
System.out.println("End");
}
}
和計時器如下:
private Handler handler = new Handler();
private Runnable updateTimer = new Runnable() {
public void run() {
System.out.println("===status===");
System.out.println(SearchTask.getStatus());
SearchTask.cancel(true);
handler.postDelayed(updateTimer, 3000);
}
};
並調用的AsyncTask和如下定時器代碼:
handler.postDelayed(updateTimer, 3000);
SearchTask SearchTask = new SearchTask();
SearchTask.execute();
doInBackground中的SearchFunction方法可能花費超過3秒鐘,因此請添加一個計時器。
但是,在updateTimer首先調用並取消AsyncTask後,doInBackground仍在運行,直到完成,然後取消onPostExecute。
我該如何取消doInBackground直接?
http://stackoverflow.com/questions/16538714/stop-asynctask-doinbackground-method/16538887。檢查這 – Raghunandan
你的意思是說你需要在3秒後取消asyntask? – Sri
更改SearchTask的對象名稱...我驚訝於您的編輯器允許相同名稱的類與同一個案例的對象.. –