Returning result from Asynctask

可紊 提交于 2019-12-01 02:01:20

Best way to get a callback from background thread is to use interfaces as a callback from AsyncTask for example:

create an interface that can be called in onPostExecute()

public interface ResponseCallback {

    void onRespond(String result);
}

and before calling asynckTask define it like this:

   ResponseCallback cpk = new ResponseCallback() {
            @Override
            public void onRespond(String result) {
              //code to be done after calling it from onPostExecute
            }
        };

and pass cpk to the constructor of of the asynckTask and call it in onPostExecute like that:

if(cpk!=null){
  cpk.onRespond(result);
}

of course you can modify the signature of the interface to what ever you want.

You need a listener. This will allow you to notify back when the AsyncTask is done.

Define the listener by creating an interface, like this:

public interface IListener 
{
    void onCompletedTask(String result);
}

On the task store a reference to the listener.

private IListener mListener;

// Pass the reference to the constructor.
public BackgroundWorker(IListener listener)
{
    mListener = listener;
}

Then you notify the listener like this.

@Override
protected void onPostExecute(String result) 
{
    mListener.onCompletedTask(result);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!