Skip to content

Instantly share code, notes, and snippets.

@yatatsu
Last active August 29, 2015 14:15
Show Gist options
  • Save yatatsu/0d3a03535b137aaa68d5 to your computer and use it in GitHub Desktop.
Save yatatsu/0d3a03535b137aaa68d5 to your computer and use it in GitHub Desktop.
package com.example.yatatsu.simpletodo.task;
import android.os.AsyncTask;
/**
* simple abstract wrapper for AsyncTask
* @author yatatsu
*/
public abstract class BaseAsyncTask<T1, T2, T3> extends AsyncTask<T1, T2, T3> {
public interface Listener<T3> {
void onSuccess(T3 result);
void onError(String error);
void onCancelled();
}
private Listener<T3> listener;
public BaseAsyncTask(Listener<T3> listener) {
super();
this.listener = listener;
}
protected String getError() {
return null;
}
protected boolean isSuccess() {
return true;
}
public void setListener(Listener<T3> listener) {
this.listener = listener;
}
public Listener<T3> getListener() {
return listener;
}
public void kill() {
cancel(true);
setListener(null);
}
@Override
protected void onPostExecute(T3 result) {
if (listener == null || isCancelled()) {
return;
}
if (isSuccess()) {
listener.onSuccess(result);
} else {
listener.onError(getError());
}
}
@Override
protected void onCancelled() {
if (listener != null) {
listener.onCancelled();
}
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onResume() {
super.onResume();
new BaseAsyncTask<String, Void, String>(this) {
@Override
protected String doInBackground(String... params) {
StringBuilder sb = new StringBuilder();
for (int i = 0, count = params.length; i < count; i++) {
sb.append(params[i]);
if (i < count - 1) {
sb.append(" ");
}
}
SystemClock.sleep(1000);
return sb.toString();
}
}.execute("A", "B", "C");
}
@Override
public void onSuccess(String result) {
Log.d("RESULT", result); // "A B C";
}
@Override
public void onError(String error) {
}
@Override
public void onCancelled() {
}
}
@gulnazghanchi
Copy link

How to implement abstract method of this AsyncTask Class ? can you please give me correct and right thing,.? I am trying to implement BaseASyncTask in my project for optimization. And I want to implement abstract method in doInBackground() method of asynctask. I m bit confused in all this.

@yatatsu
Copy link
Author

yatatsu commented Aug 5, 2015

Sorry for late reply.
I fixed code, and added a usage.
This example is sample, is not suitable for production. (It should be careful of memory leak.)

  1. Should not use inner class. (use not inner class or static inner class)
  2. kill the task when activity died.(onDestroy() is good)
  3. AsyncTask is not for long async operation. (It is for short time and related with UI one)

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