I believe that it's possible to call Java methods from (PhoneGap) Javascript.
Anyone knows how to do that?? (I know how to do it by changing the source code of PhoneGap, but I'd avoid that)
I believe that it's possible to call Java methods from (PhoneGap) Javascript.
Anyone knows how to do that?? (I know how to do it by changing the source code of PhoneGap, but I'd avoid that)
PhoneGap has a decent Plugin API. You'd write the plugin in Java by implementing the IPlugin interface. Most of the magic is in the execute() function.
The best way to start writing a plugin is by writing the javascript API first. You would typical start by writing a custom javascript class, and in each method on the javascript class, marshal the variables and call into the plugin you developed using the Phonegap.exec() method. Here is the method signature for your reference.
You also need to register the Plugin. You do this by adding the registration code at the bottom of your custom javascript library.
In the example below, the author defined a javascript BarcodeScanner class and registers it using the addConstructor method.
Two steps are carried out in the addConstructor:
Create a new instance of BarcodeScanner in javascript and registers it. This is accessible in javascript as window.plugins.barcodeScanner
Registers the custom Plugin class with a service name. This service name is passed in as the first argument to PhoneGap.exec so that PhoneGap can instantiate the java plugin class and call the execute() method on it.
Sample registration code:
a simpler form:
If anyone gets nullPointer exception using the code above, do super.oncreate() first and then super..init()
I found this solution here: Phonegap Google Group
Thanks a lot to @zorglub76 for the solution....
addJavaScriptInterface(mc, "MyCls")
without Gapinit()
ed may cause crush of the app, you'd better addsuper.init()
beforeaddJavascriptInterface()
Communication from JavaScript to native is achieved by overriding the JavaScript prompt function in the Android native code and the message passed is much like that used in iOS. We used to use WebView.addJavascriptInterface to add Java objects directly to the JavaScript sandbox but that was causing some devices to crash with Android 2.3. To call JavaScript from native we currently use WebView.loadUrl(”javascript:…”) but that has some problems so we are soon moving over to polling a Java message queue calling a local HTTP server via a long-lived XHR connection.
Description by here
I finally made it work.
Create a class with methods you want to use:
In your main activity add a Javascript interface for this class:
In Javascript call window.MyCls methods:
Note:
As mentioned in the comment, for Android version 4.2 and above, add
@JavascriptInterface
to the method which you want to access from your HTML page. Reference.