views:

78

answers:

2

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);
        }   
    }
}
+1  A: 

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.

Walter Mundt
PrintStatusTask does exit after the task completes. But addingthis.cancel(true) to onPostExecute() in PrintStatusTask (see updated snippet) also does not kill the task. I suppose the task will go away after it drains the battery and the device is off, but don't like that workaround. Any other ideas?
JackN
Calling `cancel` in `onPostExecute` is useless, because that only gets called after the task completes or is canceled. You have to call it elsewhere. For example, if you add an `AsyncTask` field to your `Activity` and save the task there when you create it, you can later do `mPrintTask.cancel` on your activity's `onDestroy`, if that's appropriate. You have to choose the lifecycle of your task before you can find an appropriate place to cancel it, of course.
Walter Mundt
That is what I thought. Except that onPostExecute does get called, but the AsyncTask is still shown as running in the debug window. Is this possibly a defect in the Eclipse/Android environment that does not properly remove the AsyncTask indication from the debug window, even though the task has actually exited?
JackN
+1  A: 

I found a good answer here.

JackN