Skip to content

Instantly share code, notes, and snippets.

@cesarferreira
Last active February 22, 2021 20:48
Show Gist options
  • Star 36 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save cesarferreira/ef70baa8d64f9753b4da to your computer and use it in GitHub Desktop.
Save cesarferreira/ef70baa8d64f9753b4da to your computer and use it in GitHub Desktop.
Advanced Android AsyncTask Callback example
package com.cesarferreira.asynctaskcallback;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SomeTask someTask = new SomeTask(getApplicationContext(), new OnEventListener<String>() {
@Override
public void onSuccess(String result) {
Toast.makeText(getApplicationContext(), "SUCCESS: "+result, Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Exception e) {
Toast.makeText(getApplicationContext(), "ERROR: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
someTask.execute();
}
}
package com.cesarferreira.asynctaskcallback;
/**
* Created by cesarferreira on 30/05/14.
*/
public interface OnEventListener<T> {
public void onSuccess(T object);
public void onFailure(Exception e);
}
package com.cesarferreira.asynctaskcallback;
import android.content.Context;
import android.os.AsyncTask;
/**
* Created by cesarferreira on 22/05/14.
*/
public class SomeTask extends AsyncTask<Void, Void, String> {
private OnEventListener<String> mCallBack;
private Context mContext;
public Exception mException;
public SomeTask(Context context, OnEventListener callback) {
mCallBack = callback;
mContext = context;
}
@Override
protected String doInBackground(Void... params) {
try {
// todo try to do something dangerous
return "HELLO";
} catch (Exception e) {
mException = e;
}
return null;
}
@Override
protected void onPostExecute(String result) {
if (mCallBack != null) {
if (mException == null) {
mCallBack.onSuccess(result);
} else {
mCallBack.onFailure(mException);
}
}
}
}
@inngage
Copy link

inngage commented Sep 7, 2016

Tnx nice approach!

@galihazizif
Copy link

thankyou....

@RabaHub
Copy link

RabaHub commented Jul 11, 2018

like!

@shinip2
Copy link

shinip2 commented Apr 25, 2019

Thanks a lot!

@vashli
Copy link

vashli commented Jul 30, 2019

Very Decent Approach.

@vjcodeforgood
Copy link

how to unit test?

@Miha-x64
Copy link

This SomeTask leaks context because there's no cancellation.

@pingothedoer
Copy link

Clean

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