开发者

Is there any AJAX-like asynchronous callback method in Android?

开发者 https://www.devze.com 2023-02-16 07:54 出处:网络
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 loo

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:

  1. Client sends data through POST or GET to the server and the app is not locked, waiting for response.
  2. Server process the data and sends a response.
  3. 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();
    }
}));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号