Skip to content

Instantly share code, notes, and snippets.

@akhy
Created August 23, 2013 10:24
Show Gist options
  • Save akhy/6317789 to your computer and use it in GitHub Desktop.
Save akhy/6317789 to your computer and use it in GitHub Desktop.
Wrapper abstract class for Android's built-in AsyncTask with weak reference to target object. For example you can do any image processing in background (asynchronously) and set the output to a garbage collectible ImageView once completed. If for some reason the ImageView isn't available anymore (e.g. due to user switching activity), the `applyOu…
package net.akhyar.android.async;
import java.lang.ref.WeakReference;
import android.os.AsyncTask;
public abstract class WeakTask<I, O, T> extends AsyncTask<Void, Void, O> {
protected final WeakReference<T> targetRef;
protected I input;
public WeakTask(I input, T target) {
this.input = input;
targetRef = new WeakReference<T>(target);
}
@Override
protected O doInBackground(Void... args) {
return process(input);
}
protected abstract O process(I input);
@Override
protected void onPostExecute(O output) {
final T target = targetRef.get();
if (target != null)
applyOutputToTarget(output, target);
}
protected abstract void applyOutputToTarget(O output, T target);
}
@akhy
Copy link
Author

akhy commented Aug 23, 2013

Sample usage:

// decode file in background and set the result to an ImageView (weak referenced)
new WeakTask<String, Bitmap, ImageView>(path, imgPreview) {

    @Override
    protected Bitmap process(String path) {
        return BitmapFactory.decodeFile(path, null);
    }

    @Override
    protected void applyOutputToTarget(Bitmap result, ImageView target) {
        target.setImageBitmap(result);

        ............
    }
}.execute();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment