Skip to content

Instantly share code, notes, and snippets.

@extralam
Created December 22, 2014 03:24
Show Gist options
  • Save extralam/c070f8c07dd8113a84d2 to your computer and use it in GitHub Desktop.
Save extralam/c070f8c07dd8113a84d2 to your computer and use it in GitHub Desktop.
Extends AsyncTask , Check Activity finished or not before send back to UI Thread. and change execute to THREAD_POOL_EXECUTOR
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Build;
import java.lang.ref.WeakReference;
abstract public class SimpleBackgroundTask<T> extends AsyncTask<Object, Void, T> {
private WeakReference<Activity> weakActivity;
public SimpleBackgroundTask(Activity activity) {
weakActivity = new WeakReference<Activity>(activity);
}
@Override
protected final T doInBackground(Object... voids) {
return onRun(voids);
}
private boolean canContinue() {
Activity activity = weakActivity.get();
return activity != null && !activity.isFinishing() ;
}
public Activity getActivity(){
return weakActivity.get();
}
@Override
protected void onPostExecute(T t) {
if(weakActivity != null && canContinue()) {
onSuccess(t);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public SimpleBackgroundTask execute() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return(this);
}
return (SimpleBackgroundTask)(super.execute());
}
abstract protected T onRun(Object... voids);
abstract protected void onSuccess(T result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment