开发者

What kills an Android AsyncTask? [duplicate]

This question already has answers here: AsyncTask threads never die (4 answers)开发者_如何学编程 Closed 3 years ago.

PrintStatusTask parses the contents of a gmail inbox looking for various items of interest to report on. But a new AsyncTask is created for each PrintStatusTask().execute() according to the debugger. Shouldn't these tasks die on exit? Do they have to be killed manually?

public class Controller extends Activity {
    ...
    private boolean applyMenuChoice(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menuStatus:
            new PrintStatusTask().execute();
            ...
    class PrintStatusTask extends AsyncTask<Void, String, Void> {
        @Override
        protected Void doInBackground(Void... unused) {
            ...
            return null;
        }
        @Override
        protected void onPostExecute(Void unused) {
            this.cancel(true);
        }   
    }
}


Ok guys I'm sorry but I have to tell you you are wrong. An AsyncTask is (almost) NEVER killed. Calling AsyncTask.cancel will NOT kill the task.

Quoted From the documentation of AsyncTask

A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)

reading docs can be useful... So i'll sum it up for you, but since I already answered in another post, I send you to it : How can I make asynchronous URL connections on Android?

I gave a workaround to your problem, and yes, some time, some AsyncTask are killed. But I won't recommend using them, they're useless. But since, your AsyncTasks running should show a "waiting" status if they're done with the task. Otherwise your task is NOT done, and I never heard about some adb thread watching bug.

Regards !


If you keep a reference to the task around, you can call its cancel method to cancel it. Otherwise, they live as long as your app's process does, or until they return from the doInBackground and (if present) onPostExecute functions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜