Search code examples
androidcordovapluginssencha-touch-2

Cordova plugin - Javascript receive message from native code


As the following documentation here: http://docs.phonegap.com/en/3.5.0/guide_platforms_android_plugin.md.html#Android%20Plugins

I override an method

 @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if ("beep".equals(action)) {
            this.beep(args.getLong(0));
            callbackContext.success();
            return true;
        }
        return false;  // Returning false results in a "MethodNotFound" error.
    }

And call it from Javascript like this:

cordova.exec(<successFunction>, <failFunction>, <service>, <action>, [<args>]);

Above java native code only return an boolean result. How to make it return an string ( or JSON ) and make cordova.exec() receive it ?

p/s: I want to use java native code read a JSON string (List of items) from email. And it will return to Javascript code to render to an list in Sencha Touch


Solution

  • The answer to your question is provided in the documentation page you linked. Check the last code example on the page:

    private void echo(String message, CallbackContext callbackContext) {
            if (message != null && message.length() > 0) {
                callbackContext.success(message); //<-THIS LINE
            } else {
                callbackContext.error("Expected one non-empty string argument.");
            }
        }
    

    According to documentation: "the callbackContext.success() passes the original message string back to JavaScript's success callback as a parameter."

    So in JS, if you define success callback function like:

    function onSuccess(message){
         console.log(message);
    }
    

    and call it:

    cordova.exec(onSuccess, ...)
    

    It should output contents of the passed message string parameter on success.