I was wondering if there is any way to create asynchronous callback functions in an android client similar to AJAX, binding an event handler to a开发者_运维知识库 'response received' event. I am looking for something like this:
- Client sends data through POST or GET to the server and the app is not locked, waiting for response.
- Server process the data and sends a response.
- The app receives the response and at this time an event is raised and its event handler is executed.
AsyncTask is all you need. http://developer.android.com/reference/android/os/AsyncTask.html
You can use droidQuery to use Ajax-like syntax. This library uses an AsyncTask to run the requests in the background. A simple example:
$.ajax(new AjaxOptions().url("http://www.example.com").type("GET").dataType("json").success(new Function() {
@Override
public void invoke($ d, Object... args) {
JSONObject json = (JSONObject) args[0];
//TODO handle json. If expecting a JSONArray, just cast args[0] to JSONArray.
}
}).error(new Function() {
@Override
public void invoke($ d, Object... args) {
AjaxError error = (AjaxError) args[0];
Toast.makeText(MyActivity.this, "Error (" + error.status + "): " + error.reason, Toast.LENGTH_LONG).show();
}
}));
精彩评论