解析PhoneGap插件如何使用
PhoneGap插件如何使用是本文要介紹的內(nèi)容,主要是來了解并學(xué)習(xí)PhoneGap中插件的內(nèi)容,PhoneGap是一個開源的開發(fā)框架,用來構(gòu)建跨平臺的使用HTML,CSS和JavaScript的移動應(yīng)用程序,來看詳細(xì)內(nèi)容講解。
一、PhoneGap平臺
前不久PhoneGap發(fā)布了1.0版本,這為移動開發(fā)大家族提供了又一個跨平臺的解決方案。開發(fā)者只要有JavaScript、CSS3、Html5的基礎(chǔ)就可以快速開發(fā)移動應(yīng)用,并且一次開發(fā)支持iOS、iOS(xcode 4)、Android、WebOS、Blackberry、Symbian 六大平臺。
不過,JavaScript的速度雖然在近些年提高了100倍,其速度還是無法和原生代碼相比。在編寫復(fù)雜的業(yè)務(wù)邏輯時JavaScript顯得力不從心。那么PhoneGap有沒有辦法解決這個問題呢?答案是肯定的。PhoneGap平臺提供了插件功能,開發(fā)者可以將重量級的功能封裝在原生代碼開發(fā)的插件中,并將接口暴露給JavaScript,JavaScript在調(diào)用插件功能時都是非阻塞的,所以并不影響JavaScript層的性能。下面我們就看看如何編寫和調(diào)用一個PhoneGap插件吧。
二、編寫插件
由于要寫原生代碼,所以各個平臺插件的編寫略有不同。我們以Android為例吧。
1、插件功能
PhoneGap提供了文件讀寫的Api,但沒有提供列出文件清單的功能。我們編寫一個名為 DirectoryListingPlugin 的插件來實現(xiàn)列表SDCARD上文件的功能吧。
2、創(chuàng)建一個Android工程
如下圖所示:
3、包含PhoneGap依賴
下載PhoneGap并解壓
在工程根目錄新建目錄/libs
拷貝 phonegap.jar 到 /libs
注:由于是寫插件,所以只有phonegap.jar就夠了。要建立完整的PhoneGap應(yīng)用,可參考
- http://www.phonegap.com/start/#android
4、實現(xiàn)插件類
代碼:
- /**
- * Example of Android PhoneGap Plugin
- */
- package com.trial.phonegap.plugin.directorylisting;
- import java.io.File;
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
- import android.util.Log;
- import com.phonegap.api.Plugin;
- import com.phonegap.api.PluginResult;
- import com.phonegap.api.PluginResult.Status;
- /**
- * PhoneGap plugin which can be involved in following manner from javascript
- * <p>
- * result example -
- * {"filename":"/sdcard","isdir":true,"children":[{"filename":"a.txt"
- * ,"isdir":false},{..}]}
- * </p>
- *
- * <pre>
- * {@code
- * successCallback = function(result){
- * //result is a json
- *
- * }
- * failureCallback = function(error){
- * //error is error message
- * }
- *
- * DirectoryListing.list("/sdcard",
- * successCallback
- * failureCallback);
- *
- * }
- * </pre>
- *
- * @author Rohit Ghatol
- *
- */
- public class DirectoryListPlugin extends Plugin {
- /** List Action */
- public static final String ACTION = "list";
- /*
- * (non-Javadoc)
- *
- * @see com.phonegap.api.Plugin#execute(java.lang.String,
- * org.json.JSONArray, java.lang.String)
- */
- @Override
- public PluginResult execute(String action, JSONArray data, String callbackId) {
- Log.d("DirectoryListPlugin", "Plugin Called");
- PluginResult result = null;
- if (ACTION.equals(action)) {
- try {
- String fileName = data.getString(0);
- JSONObject fileInfo = getDirectoryListing(new File(fileName));
- Log
- .d("DirectoryListPlugin", "Returning "
- + fileInfo.toString());
- result = new PluginResult(Status.OK, fileInfo);
- } catch (JSONException jsonEx) {
- Log.d("DirectoryListPlugin", "Got JSON Exception "
- + jsonEx.getMessage());
- result = new PluginResult(Status.JSON_EXCEPTION);
- }
- } else {
- result = new PluginResult(Status.INVALID_ACTION);
- Log.d("DirectoryListPlugin", "Invalid action : " + action
- + " passed");
- }
- return result;
- }
- /**
- * Gets the Directory listing for file, in JSON format
- *
- * @param file
- * The file for which we want to do directory listing
- * @return JSONObject representation of directory list. e.g
- * {"filename":"/sdcard"
- * ,"isdir":true,"children":[{"filename":"a.txt"
- * ,"isdir":false},{..}]}
- * @throws JSONException
- */
- private JSONObject getDirectoryListing(File file) throws JSONException {
- JSONObject fileInfo = new JSONObject();
- fileInfo.put("filename", file.getName());
- fileInfo.put("isdir", file.isDirectory());
- if (file.isDirectory()) {
- JSONArray children = new JSONArray();
- fileInfo.put("children", children);
- if (null != file.listFiles()) {
- for (File child : file.listFiles()) {
- children.put(getDirectoryListing(child));
- }
- }
- }
- return fileInfo;
- }
- }
- /**
- * Example of Android PhoneGap Plugin
- */
- package com.trial.phonegap.plugin.directorylisting;
- import java.io.File;
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
- import android.util.Log;
- import com.phonegap.api.Plugin;
- import com.phonegap.api.PluginResult;
- import com.phonegap.api.PluginResult.Status;
- /**
- * PhoneGap plugin which can be involved in following manner from javascript
- * <p>
- * result example -
- * {"filename":"/sdcard","isdir":true,"children":[{"filename":"a.txt"
- * ,"isdir":false},{..}]}
- * </p>
- *
- * <pre>
- * {@code
- * successCallback = function(result){
- * //result is a json
- *
- * }
- * failureCallback = function(error){
- * //error is error message
- * }
- *
- * DirectoryListing.list("/sdcard",
- * successCallback
- * failureCallback);
- *
- * }
- * </pre>
- *
- * @author Rohit Ghatol
- *
- */
- public class DirectoryListPlugin extends Plugin {
- /** List Action */
- public static final String ACTION = "list";
- /*
- * (non-Javadoc)
- *
- * @see com.phonegap.api.Plugin#execute(java.lang.String,
- * org.json.JSONArray, java.lang.String)
- */
- @Override
- public PluginResult execute(String action, JSONArray data, String callbackId) {
- Log.d("DirectoryListPlugin", "Plugin Called");
- PluginResult result = null;
- if (ACTION.equals(action)) {
- try {
- String fileName = data.getString(0);
- JSONObject fileInfo = getDirectoryListing(new File(fileName));
- Log
- .d("DirectoryListPlugin", "Returning "
- + fileInfo.toString());
- result = new PluginResult(Status.OK, fileInfo);
- } catch (JSONException jsonEx) {
- Log.d("DirectoryListPlugin", "Got JSON Exception "
- + jsonEx.getMessage());
- result = new PluginResult(Status.JSON_EXCEPTION);
- }
- } else {
- result = new PluginResult(Status.INVALID_ACTION);
- Log.d("DirectoryListPlugin", "Invalid action : " + action
- + " passed");
- }
- return result;
- }
- /**
- * Gets the Directory listing for file, in JSON format
- *
- * @param file
- * The file for which we want to do directory listing
- * @return JSONObject representation of directory list. e.g
- * {"filename":"/sdcard"
- * ,"isdir":true,"children":[{"filename":"a.txt"
- * ,"isdir":false},{..}]}
- * @throws JSONException
- */
- private JSONObject getDirectoryListing(File file) throws JSONException {
- JSONObject fileInfo = new JSONObject();
- fileInfo.put("filename", file.getName());
- fileInfo.put("isdir", file.isDirectory());
- if (file.isDirectory()) {
- JSONArray children = new JSONArray();
- fileInfo.put("children", children);
- if (null != file.listFiles()) {
- for (File child : file.listFiles()) {
- children.put(getDirectoryListing(child));
- }
- }
- }
- return fileInfo;
- }
- }
5、將插件類導(dǎo)出成jar 包
Eclipse中如下操作:
在要生成jar的項目上右擊,選擇菜單上的Export(導(dǎo)出)
導(dǎo)出類型選擇Jar File
選擇或者輸入生成路徑
選擇要導(dǎo)出的類
我們導(dǎo)出成directorylist.jar
6、實現(xiàn)JavaScript插件
創(chuàng)建一個名為DirectoryListing的類
創(chuàng)建一個成員函數(shù)list()
在成員函數(shù)中調(diào)用
- PhoneGap.exec(<<successCallback>>,<<failureCallback>>,<<Plugin Name>>,<<Action Name>>,<<Arguments Array>>);
將js文件保存為directorylisting.js
代碼:
- /**
- *
- * @return Object literal singleton instance of DirectoryListing
- */
- var DirectoryListing = {
- /**
- * @param directory The directory for which we want the listing
- * @param successCallback The callback which will be called when directory listing is successful
- * @param failureCallback The callback which will be called when directory listing encouters an error
- */
- list: function(directory,successCallback, failureCallback) {
- return PhoneGap.exec(successCallback, //Success callback from the plugin
- failureCallback, //Error callback from the plugin
- 'DirectoryListPlugin', //Tell PhoneGap to run "DirectoryListingPlugin" Plugin
- 'list', //Tell plugin, which action we want to perform
- [directory]); //Passing list of args to the plugin
- }
- };
- /**
- *
- * @return Object literal singleton instance of DirectoryListing
- */
- var DirectoryListing = {
- /**
- * @param directory The directory for which we want the listing
- * @param successCallback The callback which will be called when directory listing is successful
- * @param failureCallback The callback which will be called when directory listing encouters an error
- */
- list: function(directory,successCallback, failureCallback) {
- return PhoneGap.exec(successCallback, //Success callback from the plugin
- failureCallback, //Error callback from the plugin
- 'DirectoryListPlugin', //Tell PhoneGap to run "DirectoryListingPlugin" Plugin
- 'list', //Tell plugin, which action we want to perform
- [directory]); //Passing list of args to the plugin
- }
- };
三、測試
1.創(chuàng)建一個PhoneGap應(yīng)用
2.將 directorylisting.jar 加入工程依賴
3.將directorylisting.js放入到 /assets/www 目錄下。
4.在 /res/xml/plugins.xml 文件中添加 5、在index.html中調(diào)用DirectoryListing.list
代碼:
- <!DOCTYPE HTML>
- <html>
- <head>
- <title>PhoneGap</title>
- </head>
- <body>
- <!-- Button -->
- <input disabled id="list-sdcard" type="button" value="List SDCard Contents" />
- <hr>
- <!-- Place Holder for placing the SD Card Listing -->
- <div id="result"></div>
- <hr>
- <script type="text/javascript" src="phonegap-1.0.0.js"></script>
- <script type="text/javascript" src="directorylisting.js"></script>
- <script type="text/javascript" >
- document.addEventListener('deviceready', function() {
- var btn = document.getElementById("list-sdcard");
- btn.onclick = function() {
- DirectoryListing.list( "/sdcard",
- function(r){printResult(r)},
- function(e){log(e)}
- );
- }
- btn.disabled=false;
- }, true);
- function printResult(fileInfo){
- var innerHtmlText=getHtml(fileInfo);
- document.getElementById("result").innerHTML=innerHtmlText;
- }
- function getHtml(fileInfo){
- var htmlText="<ul><li>"+fileInfo.filename;
- if(fileInfo.children){
- for(var index=0;index<fileInfo.children.length;index++){
- htmlTexthtmlTexthtmlText=htmlText+getHtml(fileInfo.children[index]);
- }
- }
- htmlTexthtmlTexthtmlText=htmlText+"</li></ul>";
- return htmlText;
- }
- </script>
- </body>
- </html>
小結(jié):解析PhoneGap插件如何使用的內(nèi)容介紹完了,希望通過本文的學(xué)習(xí)能對你有所幫助!