Custom callback handler

I am trying to understand the mechanism of the callback handler. How is the handle () method called? Can someone give an example of using a special callback handler (except for those used in Login JASS modules or so) in an application without Swing?

+5
source share
2 answers

Define an interface for callback processing.

public interface ServiceListener<T> {
    void callback(T result);
}

Define a method that takes a ServiceListener as a parameter and returns void.

Public void runInBackground(ServiceListener listener) {
    ...code that runs in the background...
    listener.callback(...data to return to caller...);
}

And now you can do this from your main code:

 runInBackground(new ServiceListener() {


        @Override
        public void callback(..returned data...) {
            ...Do stuff with returned data...
        }
 });
+9
source

This is a basic example of requesting data from a web server using AsyncTask from an Android application.

async. , , .

public class Webservice extends AsyncTask<String, Void, String> {
    private DialogListener dialogListener;

    public Webservice(final DialogListener dialogListener) {
        this.dialogListener = dialogListener; 
    }

    @Override
    protected String doInBackground(final String... strings) {
        // We cant trigger onComplete here as we are not on the GUI thread!
        return "";
    }

    protected void onPostExecute(final String result) {
        dialogListener.onComplete(result);
    }   
}

:

public class Server {
    public void queryServer(final String url, final DialogListener service) {
        // Simulate slow network...
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Webservice(service).execute(url);
    }
}

, , , , async.

Server s = new Server();

        // Async server call. 
        s.queryServer("http://onto.dk/actions/searchEvents.jsp?minLatE6=55640596&minLngE6=12078516&maxLatE6=55642654&maxLngE6=12081948", new DialogListener() {
        @Override
        public void onComplete(final String result) {
            toast("complete");
        }

        @Override
        public void onError() {
            toast("error");
        }
    });
+3

All Articles