在用Phonegap开发时,需要进行前后台数据交互,在网上找资料,很多东西让人一头雾水,最后借鉴了下面的博客:
http://blog.sina.com.cn/s/blog_681929ae010177qt.html
才实现了一个简单数据交互
1:定义名称为FilePlugin的 Class文件继承自Plugin;需要实现execute方法
package qj; import org.json.JSONArray; import android.webkit.WebSettings.PluginState; import com.phonegap.api.Plugin; import com.phonegap.api.PluginResult; public class FilePlugin extends Plugin{//继承 @Override public PluginResult execute(String action, JSONArray args, String callbackId) { PluginResult pr=new PluginResult(PluginResult.Status.OK, "进入"); String ls=action; String lss=args.toString(); try { ls = java.net.URLDecoder.decode(ls,"UTF-8"); lss = new String(lss.getBytes("iso-8859-1"),"utf-8"); lss = java.net.URLDecoder.decode(lss,"UTF-8"); if (action.equals("createFile")) { String filePath = "文件路径!"; pr=new PluginResult(PluginResult.Status.OK,filePath); } if(action.equals("read")){ pr=new PluginResult(PluginResult.Status.OK, "文件读取"); } } catch (Exception e) { return new PluginResult(PluginResult.Status.ERROR,e.getMessage()); } return pr; } }
2:定义名称为file的js文件,用以实现方法并且注册成为Phonegap的插件。
var FilePlugin = function(){}; FilePlugin.prototype.write = function(fileName, content, successCallback, failureCallback){ return PhoneGap.exec(successCallback, failureCallback, "FilePlugin", "write", [fileName, content]); }; FilePlugin.prototype.overWrite = function(srcName, destName,successCallback, failureCallback){ return PhoneGap.exec(successCallback, failureCallback, "FilePlugin", "orverwrite", [srcName, destName]); }; FilePlugin.prototype.read = function(filePath,successCallback, failureCallback){ return PhoneGap.exec(successCallback, failureCallback, "FilePlugin", "read", [filePath]); }; //注册插件 PhoneGap.addConstructor(function(){ PhoneGap.addPlugin("file", new FilePlugin()); });
3:管理Class文件与Js文件
在xml中的plugins.xml中配置
name="类名称"
value="命名空间"
<plugin name="FilePlugin" value="qj.FilePlugin"/>
4:页面调用
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="UTF-8" src="phonegap-1.0.0.js"></script> <script type="text/javascript" charset="UTF-8" src="file.js"></script> <script type="text/javascript" charset="UTF-8"> function read(){ window.plugins.file.read("file.txt", success, failure); var arg= encodeURI(encodeURI("中文")); arg= "中文"; //FilePlugin.prototype.read(arg, success, failure); } function success(r){ alert("success:"+r); }; function failure(e){ alert("failure:"+e); }; </script> <button onclick="read()">read Some</button>