How to get callback from Asynctask android
Posted By : Chandan Wadhwa | 27-Dec-2015
Callback is a very common requirement in programming language. A callback function is essential requirement for common problem and therefore we use callback patteren.
But unfortunately Asyc task in not designed to get callback. We have to use interface for receiving callback from asynctask.
Given is the explanation to get callback from async task.
1) Create Interface and define method for callback.
public interface AsyncResponse {
void processFinish(String output);
}
2) Create async task with a constructor to pass reference to interface
public class CallApi extends AsyncTask{ public AsyncResponse delegate = null;//Call back interface public CallApi(AsyncResponse asyncResponse) { delegate = asyncResponse;//Assigning call back interface through constructor } @Override protected String doInBackground(String... params) { //Your network call or background process comes here return res; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected void onPostExecute(String aVoid) { super.onPostExecute(aVoid); delegate.processFinish(aVoid); } }
3) Get Callback from asynctask
Instantiate Asynctask class and override interface method to get callback
CallApi callApi=new CallApi(new AsyncResponse() {
@Override
public void processFinish(String callbackResponse) {
Log.d("Callback response ->", callbackResponse);
//process after callback
}
});
callApi.execute("http://example.com");
Thanks.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Chandan Wadhwa
Chandan is an Android Apps developer with good experience in building native Android applications.