How to get callback from Asynctask android

Posted By : Chandan Wadhwa | 27-Dec-2015

Callback Asynctask Android

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.

 

About Author

Author Image
Chandan Wadhwa

Chandan is an Android Apps developer with good experience in building native Android applications.

Request for Proposal

Name is required

Comment is required

Sending message..