在用Phonegap開發時,須要進行先後臺數據交互,在網上找資料,不少東西讓人一頭霧水,最後借鑑了下面的博客:javascript
http://blog.sina.com.cn/s/blog_681929ae010177qt.htmlhtml
才實現了一個簡單數據交互java
1:定義名稱爲FilePlugin的 Class文件繼承自Plugin;須要實現execute方法android
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的插件。web
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文件json
在xml中的plugins.xml中配置api
name="類名稱"ide
value="命名空間"spa
<plugin name="FilePlugin" value="qj.FilePlugin"/>
4:頁面調用.net
<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>