Reputation: 21895
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 accomplish this?
Upvotes: 2
Views: 6926
Reputation: 23883
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="com.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);
}
Upvotes: 7