js通过PhoneGap调用Java方法html 传参,并互相传递参数。
1.JAVA代码
编写一个继承Plugin的类html 传参,并重绘执行技能。
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 { JSONObject jsonObj = new JSONObject();//可以返回给JS的JSON数据 if (action.equals("hello")) { String str1= args.getString(0); //获取第一个参数 String str2= args.getString(1); //获取第二个参数 jsonObj.put("str1", str1+"1"); //把参数放到JSONObject对象中 jsonObj.put("str2", str2+"2"); //把参数放到JSONObject对象中 } PluginResult r = new PluginResult(PluginResult.Status.OK,jsonObj); return r; } catch (Exception e) { e.printStackTrace(); } } }
创建一个新的 .js 文件并将其放置在与phonegap 文件相同的目录中。 (创建一个新的 simplePlugin.js 文件)
var SimplePlugin = function() {}; //str1和str2是传到JAVA的参数 SimplePlugin.prototype.hello = function(successCallback, failureCallback, str1, str2) { // exec 內的參數分別是: Success Callback, Failure Callback, Registered Plugin name:就是在XML文件配置的那个所对应的name, // 'hello'是传入Java文件的execute方法中的参数String action // name (從 HTML 傳進來的參數) return PhoneGap.exec(successCallback, failureCallback, 'PluginTest', 'hello', [str1,str2]); }; // 这里是 PhoneGap Plugin 的註冊,Plugin 的名稱還有 Native Class 的名稱別打錯了,就是我們剛剛輸入的那些 PhoneGap.addConstructor(function() { // Register the javascript plugin with PhoneGap PhoneGap.addPlugin('simpleplugin', new SimplePlugin()); //simpleplugin是插件名称, new SimplePlugin()实例化的是本Javascript的类名 });
4. HTML文件中调用方法
在html文件中引入phonegap和插件的js文件,并调用
JAVA传参 $(document).ready(function(e) { $("#btn_test").click(function(){ window.plugins.simplePlugin.hello( function(result) { alert("返回的第一个参数:"+result.str1+"返回的第二个参数"+result.str2); }, function(error) { }, "第一个参数", "第二个参数" ); }); });
上面Js调用Java方法并互相传递参数的简单例子就是小编分享的全部内容了。 希望能给大家一个参考,也希望大家多多支持脚本之家。