Js通過PhoneGap調用Java方法並互相傳參的。
一、JAVA代碼
寫一個類,該類繼承自Plugin並重寫execute方法。
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(); } }}三、Javascript文件中註冊插件
新建一個.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的類名});四、在HTML文件中調用方法
在html文件中引入phonegap和插件的js文件,調用方法
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title>JAVA傳參</title> <script src="phonegap.js"></script> <!--phonegap包--> <script src="js/jquery.js"></script> <script src="simplePlugin.js"></script><!--自定義的插件文件--> <script> $(document).ready(function(e) { $("#btn_test").click(function(){ window.plugins.simplePlugin.hello( function(result) { alert("返回的第一個參數:"+result.str1+"返回的第二個參數"+result.str2); }, function(error) { }, "第一個參數", "第二個參數" ); }); }); </script> </head><body><button type="button" id="btn_test">Click Me!</button></body></html>以上這篇Js調用Java方法並互相傳參的簡單實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。