最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can I call a Java function from JavaScript in my CordovaPhonegap application? - Stack Overflow

programmeradmin5浏览0评论

My application uses Cordova. I need to capture a keypress in my app and then call a Java function in my Cordova app, like so:

$(document).on('keypress', function() {
    // call mySpecialFunction() Java function here
});

and then the Cordova app's main activity:

public class EndPipe extends CordovaActivity 
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        super.init();
        super.loadUrl(Config.getStartUrl());
    }

    public void mySpecialFunction() {
        // some Java code here
    }
}

How can I acplish this?

My application uses Cordova. I need to capture a keypress in my app and then call a Java function in my Cordova app, like so:

$(document).on('keypress', function() {
    // call mySpecialFunction() Java function here
});

and then the Cordova app's main activity:

public class EndPipe extends CordovaActivity 
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        super.init();
        super.loadUrl(Config.getStartUrl());
    }

    public void mySpecialFunction() {
        // some Java code here
    }
}

How can I acplish this?

Share Improve this question asked Oct 1, 2014 at 18:00 Chad JohnsonChad Johnson 21.9k36 gold badges115 silver badges218 bronze badges 1
  • 1 You will want to lookup create cordova plugin as you will need to build a cordova plugin to access native methods from JS. – Dawson Loudon Commented Oct 1, 2014 at 18:09
Add a ment  | 

1 Answer 1

Reset to default 7

you can try this one

Firstly you need to declare your custom plugin in config.xml. You can found this file in res > xml folder.

<feature name="CustomPlugin">
      <param name="android-package" value=".Phonegap.CustomPlugin" />
</feature>

Then you need to implement plugin by using Java- code

public class CustomPlugin extends CordovaPlugin {

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
            throws JSONException {

        if (action.equals("sayHello")){
            try {
                String responseText = "Hello world, " + args.getString(0);
                callbackContext.success(responseText);
            } catch (JSONException e){
                callbackContext.error("Failed to parse parameters");
            }
            return true;
        }

        return false;
    }
}

Finally we calling a plugin from javascript

function initial(){
    var name = $("#NameInput").val();
    cordova.exec(sayHelloSuccess, sayHelloFailure, "CustomPlugin", "sayHello", [name]);
}

function sayHelloSuccess(data){
    alert("OK: " + data);
}

function sayHelloFailure(data){
    alert("FAIL: " + data);
}
发布评论

评论列表(0)

  1. 暂无评论