0

Got a small issue and would like some advice on it.

This is my Async task

public class DummyTask extends AsyncTask<Void, Void, Void> {

    private OnDummyTaskComplete mOnDummyTaskComplete;

    public DummyTask(OnDummyTaskComplete listener) {
        mOnDummyTaskComplete = listener;
    }

    @Override
    protected Void doInBackground(Void... params) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        mOnDummyTaskComplete.onDummyTaskComplete();
    }
}

This is my callback

public interface OnDummyTaskComplete {
    void onDummyTaskComplete();
}

This is the activity that implements the callback starts the async task.

public class MainActivity extends ActionBarActivity implements OnDummyTaskComplete {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DummyTask dummyTask = new DummyTask(this);
        dummyTask.execute();
    } 

Do I need to dispose of the callback to avoid a memory leak? Is the following code required?

@Override
protected void onPostExecute(Void aVoid) {
    mOnDummyTaskComplete.onDummyTaskComplete();
    mOnDummyTaskComplete = null;
}
Ziem
  • 6,579
  • 8
  • 53
  • 86
Ersen Osman
  • 7,067
  • 8
  • 47
  • 80

1 Answers1

0

Do I need to dispose of the callback to avoid a memory leak?

No. Shortly after onPostExecute() is run, the AsyncTask instance will lose scope, along with its reference to mOnDummyTaskComplete. Just be sure not to reference mOnDummyTaskComplete (or anything else that may contain a reference to MainActivity) from within doInBackground; otherwise, you do open yourself up to a Context leak. See this related SO issue for details.

Community
  • 1
  • 1
pathfinderelite
  • 3,047
  • 1
  • 27
  • 30