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 主站蜘蛛池模板: 武穴市| 钟山县| 阆中市| 海林市| 兴国县| 葵青区| 红安县| 正定县| 平阳县| 广安市| 凤凰县| 古蔺县| 桃江县| 寿宁县| 思茅市| 洛阳市| 阿克陶县| 上虞市| 应用必备| 长沙县| 渭南市| 青岛市| 临武县| 南充市| 息烽县| 原平市| 徐州市| 孟村| 武邑县| 通江县| 商河县| 沙河市| 南江县| 黑河市| 平顶山市| 金昌市| 喜德县| 馆陶县| 张家口市| 滕州市| 阳原县|