JS invokes Java methods through PhoneGap and passes the reference to each other.
One, Java code
Writes a class that inherits from plugin and overrides the Execute method.
Import Org.json.JSONArray;
Import android.app.Activity;
Import Android.app.AlertDialog;
Import android.content.ActivityNotFoundException;
Import Android.content.DialogInterface;
Import android.content.Intent;
Import Android.net.Uri;
Import Android.os.Bundle;
Import com.phonegap.api.PhonegapActivity;
Import Com.phonegap.api.Plugin;
Import Com.phonegap.api.PluginResult;
public class Plugintest extends Plugin {public static String ACTION = "Hello";
Public plugintest () {}/** * Executes the request and returns Pluginresult.
* @param action the action to execute.
* @param args Jsonarray of arguments for the plugin.
* @param callbackid The callback ID used when calling back into JavaScript.
* @return a Pluginresult object with a status and message. */@Override Public Pluginresult Execute (string action, Jsonarray args, string callbackid) {try {Jsonobjec T jsonobj = new Jsonobject ()//JSON data that can be returned to JS if (Action.equaLS ("Hello")) {string str1= args.getstring (0);//Get first argument String str2= args.getstring (1);//Get second argument Jsonobj.put ("str1", str1+ "1"); Put the parameters in the Jsonobject object Jsonobj.put ("str2", str2+ "2");
Put the parameter in the Jsonobject object} pluginresult r = new Pluginresult (pluginresult.status.ok,jsonobj);
return R;
catch (Exception e) {e.printstacktrace (); }
}
}
Register plugins in JavaScript files
Create a new. js file and place the file in the same directory as the PhoneGap file. (Create a new simpleplugin.js file)
var simpleplugin = function () {};
STR1 and str2 are parameters that are uploaded to Java
SimplePlugin.prototype.hello = function (Successcallback, Failurecallback, str1, str2) {
//Exec's parameters are: Success Callback, Failure Callback, registered Plugin name: The name that corresponds to the XML file configuration,
// Hello ' is the parameter string action//name (from HTML legend) in the Execute method of the incoming Java file return
phonegap.exec (Successcallback, Failurecallback, ' plugintest ', ' hello ', [str1,str2]);
This is PhoneGap Plugin's registration, Plugin's name and Native Class name are not wrong, that's the phonegap.addconstructor we just entered
(function () {
//Register the JavaScript plugin with PhoneGap
Phonegap.addplugin (' Simpleplugin ', New Simpleplugin ()); Simpleplugin is the plug-in name, and the new Simpleplugin () instantiates the class name of this JavaScript
);
Iv. calling methods in HTML files
Introduction of PhoneGap and plug-in JS files in HTML file, calling method
The above JS call Java method and pass the reference to each other simple example is small series to share all the content, hope to give you a reference, also hope that we support cloud habitat community.