0

I have a AsyncTask as below:

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");
    }
}

And a Timer as below:

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);
    }
};

And call AsyncTask and timer code as below:

            handler.postDelayed(updateTimer, 3000);
            SearchTask SearchTask = new SearchTask();
            SearchTask.execute();

The SearchFunction method in doInBackground maybe spend more than 3 seconds, so add a timer.
But in updateTimer first call and cancel the AsyncTask, the doInBackground is still running until it finished, and then cancel onPostExecute.
How can I do to cancel doInBackground direct?

4

2 回答 2

1

基本上你不能这样做。最好的事情是当你设置cancel(true)意味着你会忽略运行在上面的代码onPostExecute()(也许在if那里放一个语句)。希望这可以帮助。

于 2013-08-07T07:35:30.650 回答
1

只需偶尔检查一下 isCancelled() 并尝试一下:

protected Object doInBackground(Object... x) {
    while (/* condition */) {
      // work...
      if (isCancelled()) break;
    }
    return null;
}
于 2013-08-07T07:36:29.597 回答