Sunday, December 4, 2011

Android AsyncTask great idea BAD implementation!

I got so tired of Memory leaks in my android application which was caused mainly by the AsyncTask object of the Android framework, so I've implemented my own as part of my "Cyborg" project, this works for me...

I can use the same instance of the task over and over and over, and to publish to the UI on a UI thread...

Shame on you Android and shame on you Google... :(

No warranty... use at your own risk!!!

I've updated this on the 16-03-2012, previous version had a design flaw.


import java.lang.ref.WeakReference;

import android.os.Handler;
import android.os.Message;


public abstract class AsyncTaskModel<Model, Progress, Result>
  extends Handler
  implements Logger {

 public void handleMessage(Message msg) {
  switch (msg.what) {
   case ProgressUpdate :
   case ExecutionCompleted :
   case ExecutionCancelled :
   case Dispose :
    model = null;
    threadReference = null;

 private static final int ProgressUpdate = 1;

 private static final int ExecutionCompleted = 2;

 private static final int ExecutionCancelled = 3;

 protected static final int Dispose = 4;

 protected Model model;

 private final String name;

 private WeakReference<Thread> threadReference;

 private volatile boolean cancelled;

 protected AsyncTaskModel(String name) {
  super(); = name;

 public final boolean isRunning() {
  return threadReference != null;

 public final void execute(Model model) {
  if (isRunning())
   throw new TaskInProcessException("Task is already running");
  this.model = model;
  cancelled = false;
  Runnable r = new Runnable() {

   public void run() {
    Result result = doInBackgroundImpl();
    Message message;
    if (cancelled)
     message = obtainMessage(ExecutionCancelled);
     message = obtainMessage(ExecutionCompleted);
    message.obj = result;
    message = obtainMessage(Dispose);
  Thread thread = new Thread(r, name);
  threadReference = new WeakReference<Thread>(thread);

 protected abstract Result doInBackgroundImpl();

 protected abstract void onProgressUpdate(Progress progress);

 public final void cancel() {
  cancelled = true;
  if (threadReference != null)

 protected void onExecutionCancelled(Result result) {}

 protected void cancelImpl() {}

 protected void onExecuteCompleted(Result result) {}

 protected void onPreExecute() {}

 public void publishProgress(Progress progress) {
  if (cancelled)
  Message message = obtainMessage(ProgressUpdate);
  message.obj = progress;

 public boolean wasCancelled() {
  return cancelled;

 public void logDebug(String debug) {

 public void logError(String error) {

 public void logError(String error, Throwable e) {
  AndroidLogImpl.LogImpl.logError(error, e);

 public void logError(Throwable e) {

 public void logInfo(String info) {

 public void logVerbose(String verbose) {

 public void logWarning(String warning) {

 public void logWarning(String warning, Throwable e) {
  AndroidLogImpl.LogImpl.logWarning(warning, e);



  1. Kenny Singer,

    FYI, the thing the original AsyncTask is missing, is an under management of the:

    public void disconnect ()
    if (mActivity != null) {
    mActivity = null;
    Log.d ("Demo", "RandomColorsTask has successfully disconnected from the activity.");
    } // end disconnect

    Mentioned in '' file...

    Together with a field of the UI component associated with the Task.

  2. Hey!! Sorry to revive this post but... why the model is never used? you put in the execute method as a parameter and then you only dispose it.

    1. doInBackgroundImpl() implementation in the inheriting Class would have access to the model and once the call to that method ends, it would nullify the model reference, thus preventing the Memory leak.