Created
December 22, 2014 03:24
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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