Skip to content

Instantly share code, notes, and snippets.

@Folyd
Created November 4, 2015 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Folyd/38ce96091f21e6fba7d5 to your computer and use it in GitHub Desktop.
Save Folyd/38ce96091f21e6fba7d5 to your computer and use it in GitHub Desktop.
import android.os.AsyncTask;
import java.lang.ref.WeakReference;
public abstract class WeakAsyncTask<Params, Progress, Result, WeakTarget> extends
AsyncTask<Params, Progress, Result> {
protected WeakReference<WeakTarget> mTarget;
public WeakAsyncTask(WeakTarget target) {
mTarget = new WeakReference<WeakTarget>(target);
}
/** {@inheritDoc} */
@Override
protected final void onPreExecute() {
final WeakTarget target = mTarget.get();
if (target != null) {
this.onPreExecute(target);
}
}
/** {@inheritDoc} */
@Override
protected final Result doInBackground(Params... params) {
final WeakTarget target = mTarget.get();
if (target != null) {
return this.doInBackground(target, params);
} else {
return null;
}
}
/** {@inheritDoc} */
@Override
protected final void onPostExecute(Result result) {
final WeakTarget target = mTarget.get();
if (target != null) {
this.onPostExecute(target, result);
}
}
protected void onPreExecute(WeakTarget target) {
// No default action
}
protected abstract Result doInBackground(WeakTarget target, Params... params);
protected void onPostExecute(WeakTarget target, Result result) {
// No default action
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment