现在的位置: 首页 > 综合 > 正文

PhoneGap插件编写

2013年08月13日 ⁄ 综合 ⁄ 共 7176字 ⁄ 字号 评论关闭
文章目录

 

一、PhoneGap平台

         前不久PhoneGap发布了1.0版本,这为移动开发大家族提供了又一个跨平台的解决方案。开发者只要有JavaScript、CSS3、Html5的基础就可以快速开发移动应用,并且一次开发支持iOS、iOS(xcode 4)、Android、WebOS、Blackberry、Symbian 六大平台。不过,JavaScript的速度虽然在近些年提高了100倍,其速度还是无法和原生代码相比。在编写复杂的业务逻辑时JavaScript显得力不从心。那么PhoneGap有没有办法解决这个问题呢?答案是肯定的。PhoneGap平台提供了插件功能,开发者可以将重量级的功能封装在原生代码开发的插件中,并将接口暴露给JavaScript,JavaScript在调用插件功能时都是非阻塞的,所以并不影响JavaScript层的性能。下面我们就看看如何编写和调用一个PhoneGap插件吧。

二、编写插件

由于要写原生代码,所以各个平台插件的编写略有不同。我们以Android为例吧。这个是PhoneGap官方的例子,原文网址:http://wiki.phonegap.com/w/page/36753494/How%20to%20Create%20a%20PhoneGap%20Plugin%20for%20Android 需要翻墙。

1.插件功能

PhoneGap提供了文件读写的Api,但没有提供列出文件清单的功能。我们编写一个名为 DirectoryListingPlugin 的插件来实现列表SDCARD上文件的功能吧。

2.创建一个Android工程

如下图所示:
step1

3.包含PhoneGap依赖

  • 下载PhoneGap并解压
  • 在工程根目录新建目录/libs
  • 拷贝 phonegap.jar 到 /libs

注:由于是写插件,所以只有phonegap.jar就够了。要建立完整的PhoneGap应用,可参考http://www.phonegap.com/start/#android 


4.实现插件类

代码:
[html]
 
            /**  
  1.  * Example of Android PhoneGap Plugin  
  2.  */  
  3. package com.trial.phonegap.plugin.directorylisting;  
  4.   
  5.   
  6. import java.io.File;  
  7.   
  8.   
  9. import org.json.JSONArray;  
  10. import org.json.JSONException;  
  11. import org.json.JSONObject;  
  12.   
  13.   
  14. import android.util.Log;  
  15.   
  16.   
  17. import com.phonegap.api.Plugin;  
  18. import com.phonegap.api.PluginResult;  
  19. import com.phonegap.api.PluginResult.Status;  
  20.   
  21.   
  22. /**  
  23.  * PhoneGap plugin which can be involved in following manner from javascript  
  24.  * <p>  
  25.  * result example -  
  26.  * {"filename":"/sdcard","isdir":true,"children":[{"filename":"a.txt"  
  27.  * ,"isdir":false},{..}]}  
  28.  * </p>  
  29.  *   
  30.  * <pre>  
  31.  * {@code  
  32.  * successCallback = function(result){  
  33.  *     //result is a json  
  34.  *    
  35.  * }  
  36.  * failureCallback = function(error){  
  37.  *     //error is error message  
  38.  * }  
  39.  *   
  40.  * DirectoryListing.list("/sdcard",  
  41.  *        successCallback  
  42.  *        failureCallback);  
  43.  *                                   
  44.  * }  
  45.  * </pre>  
  46.  *   
  47.  * @author Rohit Ghatol  
  48.  *   
  49.  */  
  50. public class DirectoryListPlugin extends Plugin {  
  51.     /** List Action */  
  52.     public static final String ACTION = "list";  
  53.   
  54.   
  55.     /*  
  56.      * (non-Javadoc)  
  57.      *   
  58.      * @see com.phonegap.api.Plugin#execute(java.lang.String,  
  59.      * org.json.JSONArray, java.lang.String)  
  60.      */  
  61.     @Override  
  62.     public PluginResult execute(String action, JSONArray data, String callbackId) {  
  63.         Log.d("DirectoryListPlugin", "Plugin Called");  
  64.         PluginResult result = null;  
  65.         if (ACTION.equals(action)) {  
  66.             try {  
  67.                 String fileName = data.getString(0);  
  68.                 JSONObject fileInfo = getDirectoryListing(new File(fileName));  
  69.                 Log  
  70.                         .d("DirectoryListPlugin", "Returning "  
  71.                                 + fileInfo.toString());  
  72.                 result = new PluginResult(Status.OK, fileInfo);  
  73.             } catch (JSONException jsonEx) {  
  74.                 Log.d("DirectoryListPlugin", "Got JSON Exception "  
  75.                         + jsonEx.getMessage());  
  76.                 result = new PluginResult(Status.JSON_EXCEPTION);  
  77.             }  
  78.         } else {  
  79.             result = new PluginResult(Status.INVALID_ACTION);  
  80.             Log.d("DirectoryListPlugin", "Invalid action : " + action  
  81.                     + " passed");  
  82.         }  
  83.         return result;  
  84.     }  
  85.   
  86.   
  87.     /**  
  88.      * Gets the Directory listing for file, in JSON format  
  89.      *   
  90.      * @param file  
  91.      *            The file for which we want to do directory listing  
  92.      * @return JSONObject representation of directory list. e.g  
  93.      *         {"filename":"/sdcard"  
  94.      *         ,"isdir":true,"children":[{"filename":"a.txt"  
  95.      *         ,"isdir":false},{..}]}  
  96.      * @throws JSONException  
  97.      */  
  98.     private JSONObject getDirectoryListing(File file) throws JSONException {  
  99.         JSONObject fileInfo = new JSONObject();  
  100.         fileInfo.put("filename", file.getName());  
  101.         fileInfo.put("isdir", file.isDirectory());  
  102.         if (file.isDirectory()) {  
  103.             JSONArray children = new JSONArray();  
  104.             fileInfo.put("children", children);  
  105.             if (null != file.listFiles()) {  
  106.                 for (File child : file.listFiles()) {  
  107.                     children.put(getDirectoryListing(child));  
  108.                 }  
  109.             }  
  110.         }  
  111.         return fileInfo;  
  112.     }  
  113. }  

5.将插件类导出成jar 包

Eclipse中如下操作:

  • 在要生成jar的项目上右击,选择菜单上的Export(导出)
  • 导出类型选择Jar
    File
  • 选择或者输入生成路径
  • 选择要导出的类

我们导出成directorylist.jar

6.实现JavaScript插件

  • 创建一个名为DirectoryListing的类
  • 创建一个成员函数list()
  • 在成员函数中调用PhoneGap.exec(<<successCallback>>,<<failureCallback>>,<<Plugin
    Name>>,<<Action Name>>,<<Arguments Array>>);
  • 将js文件保存为directorylisting.js

代码:

[javascript]
 
          /** 
  1.  *   
  2.  * @return Object literal singleton instance of DirectoryListing 
  3.  */  
  4. var DirectoryListing = {   
  5. /** 
  6.  * @param directory The directory for which we want the listing 
  7.  * @param successCallback The callback which will be called when directory listing is successful 
  8.  * @param failureCallback The callback which will be called when directory listing encouters an error 
  9.  */  
  10.     list: function(directory,successCallback, failureCallback) {  
  11.         return PhoneGap.exec(successCallback,        //Success callback from the plugin
      
  12.                              failureCallback,        //Error callback from the plugin
      
  13.                              'DirectoryListPlugin',  //Tell PhoneGap to run "DirectoryListingPlugin" Plugin
      
  14.                              'list',                 //Tell plugin, which action we want to perform
      
  15.                              [directory]);           //Passing list of args to the plugin
      
  16.     }  
  17. };  

三、测试

1.创建一个PhoneGap应用 http://www.phonegap.com/start/#android

2.将 directorylisting.jar
加入工程依赖

3.将directorylisting.js放入到
/assets/www 目录下。

4.在 /res/xml/plugins.xml 文件中添加 

[html]
<plugin name="DirectoryListPlugin" value="com.trial.phonegap.plugin.directorylisting.DirectoryListPlugin" />  

5.在index.html中调用DirectoryListing.list

代码:

[html]
        <!DOCTYPE HTML>  
  1. <html>  
  2.      <head>  
  3.           <title>PhoneGap</title>  
  4.      </head>  
  5.      <body>  
  6.           <!-- Button -->  
  7.           <input disabled id="list-sdcard" type="button" value="List SDCard Contents"  />  
  8.           <hr>  
  9.    
  10.           <!-- Place Holder for placing the SD Card Listing -->  
  11.           <div id="result"></div>  
  12.    
  13.           <hr>  
  14.    
  15.           <script type="text/javascript" src="phonegap-1.0.0.js"></script>  
  16.           <script type="text/javascript" src="directorylisting.js"></script>  
  17.           <script type="text/javascript" >  
  18.    document.addEventListener('deviceready', function() {  
  19.    var btn = document.getElementById("list-sdcard");  
  20.    btn.onclick = function() {  
  21.     DirectoryListing.list(    "/sdcard",  
  22. function(r){printResult(r)},  
  23. function(e){log(e)}  
  24. );  
  25.     }  
  26.     btn.disabled=false;  
  27.   }, true);  
  28.    
  29.    
  30.  function printResult(fileInfo){  
  31.   var innerHtmlText=getHtml(fileInfo);      
  32.   document.getElementById("result").innerHTML=innerHtmlText;  
  33.  }  
  34.    
  35.  function getHtml(fileInfo){  
  36.  var htmlText="<ul><li>"+fileInfo.filename;  
  37.  if(fileInfo.children){  
  38.    
  39.  for(var index=0;index<fileInfo.children.length;index++){  
  40.  htmlTexthtmlText=htmlText+getHtml(fileInfo.children[index]);  
  41.  }  
  42.  }  
  43.  htmlTexthtmlText=htmlText+"</li></ul>";  
  44.  return htmlText;  
  45.    
  46.  }   
  47.           </script>  
  48.    
  49.      </body>  
  50. </html>  

至此,一个PhoneGap Android插件就成完了。

抱歉!评论已关闭.