Js调用Java方法并互相传参的简单实例
Js通过PhoneGap调用Java方法并互相传参的。
一、JAVA代码
写一个类,该类继承自Plugin并重写execute方法。
importorg.json.JSONArray;
importandroid.app.Activity;
importandroid.app.AlertDialog;
importandroid.content.ActivityNotFoundException;
importandroid.content.DialogInterface;
importandroid.content.Intent;
importandroid.net.Uri;
importandroid.os.Bundle;
importcom.phonegap.api.PhonegapActivity;
importcom.phonegap.api.Plugin;
importcom.phonegap.api.PluginResult;
publicclassPluginTestextendsPlugin{
publicstaticStringACTION="hello";
publicPluginTest(){
}
/**
*ExecutestherequestandreturnsPluginResult.
*
*@paramactionTheactiontoexecute.
*@paramargsJSONArrayofargumentsfortheplugin.
*@paramcallbackIdThecallbackidusedwhencallingbackintoJavaScript.
*@returnAPluginResultobjectwithastatusandmessage.
*/
@Override
publicPluginResultexecute(Stringaction,JSONArrayargs,StringcallbackId){
try{
JSONObjectjsonObj=newJSONObject();//可以返回给JS的JSON数据
if(action.equals("hello")){
Stringstr1=args.getString(0);//获取第一个参数
Stringstr2=args.getString(1);//获取第二个参数
jsonObj.put("str1",str1+"1");//把参数放到JSONObject对象中
jsonObj.put("str2",str2+"2");//把参数放到JSONObject对象中
}
PluginResultr=newPluginResult(PluginResult.Status.OK,jsonObj);
returnr;
}catch(Exceptione){
e.printStackTrace();
}
}
}
三、Javascript文件中注册插件
新建一个.js文件,并把该文件和phonegap文件放在同一目录。(新建一个simplePlugin.js文件)
varSimplePlugin=function(){};
//str1和str2是传到JAVA的参数
SimplePlugin.prototype.hello=function(successCallback,failureCallback,str1,str2){
//exec內的參數分別是:SuccessCallback,FailureCallback,RegisteredPluginname:就是在XML文件配置的那个所对应的name,
//'hello'是传入Java文件的execute方法中的参数Stringaction
//name(從HTML傳進來的參數)
returnPhoneGap.exec(successCallback,failureCallback,'PluginTest','hello',[str1,str2]);
};
//这里是PhoneGapPlugin的註冊,Plugin的名稱還有NativeClass的名稱別打錯了,就是我們剛剛輸入的那些
PhoneGap.addConstructor(function(){
//RegisterthejavascriptpluginwithPhoneGap
PhoneGap.addPlugin('simpleplugin',newSimplePlugin());//simpleplugin是插件名称,newSimplePlugin()实例化的是本Javascript的类名
});
四、在HTML文件中调用方法
在html文件中引入phonegap和插件的js文件,调用方法
<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf-8">
<title>JAVA传参</title>
<scriptsrc="phonegap.js"></script><!--phonegap包-->
<scriptsrc="js/jquery.js"></script>
<scriptsrc="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>
<buttontype="button"id="btn_test">ClickMe!</button>
</body>
</html>
以上这篇Js调用Java方法并互相传参的简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。