PhoneGap 插件簡介

#廣州# OSC源創會第31期(12月27日)開始報名,OSC自曝家醜! javascript

1、PhoneGap平臺

前不久PhoneGap發佈了1.0版本,這爲移動開發你們族提供了又一個跨平臺的解決方案。開發者只要有JavaScript、CSS三、Html5的基礎就能夠快速開發移動應用,而且一次開發支持iOS、iOS(xcode 4)、Android、WebOS、Blackberry、Symbian 六大平臺。不過,JavaScript的速度雖然在近些年提升了100倍,其速度仍是沒法和原生代碼相比。在編寫複雜的業務邏輯時JavaScript顯得力不從心。那麼PhoneGap有沒有辦法解決這個問題呢?答案是確定的。PhoneGap平臺提供了插件功能,開發者能夠將重量級的功能封裝在原生代碼開發的插件中,並將接口暴露給JavaScript,JavaScript在調用插件功能時都是非阻塞的,因此並不影響JavaScript層的性能。下面咱們就看看如何編寫和調用一個PhoneGap插件吧。 html

2、編寫插件

因爲要寫原生代碼,因此各個平臺插件的編寫略有不一樣。咱們以Android爲例吧。這個是PhoneGap官方的例子,原文網址: http://wiki.phonegap.com/w/page/36753494/How%20to%20Create%20a%20PhoneGap%20Plugin%20for%20Android 須要翻*牆。

1.插件功能

PhoneGap提供了文件讀寫的Api,但沒有提供列出文件清單的功能。咱們編寫一個名爲 DirectoryListingPlugin 的插件來實現列表SDCARD上文件的功能吧。 java

2.建立一個Android工程

以下圖所示: 
step1 

 

3.包含PhoneGap依賴

  • 下載PhoneGap並解壓
  • 在工程根目錄新建目錄/libs
  • 拷貝 phonegap.jar 到 /libs
注:因爲是寫插件,因此只有phonegap.jar就夠了。要創建完整的PhoneGap應用,可參考http://www.phonegap.com/start/#android  

4.實現插件類


 

代碼:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/**
 * Example of Android PhoneGap Plugin
 */
packagecom.trial.phonegap.plugin.directorylisting;
 
 
importjava.io.File;
 
 
importorg.json.JSONArray;
importorg.json.JSONException;
importorg.json.JSONObject;
 
 
importandroid.util.Log;
 
 
importcom.phonegap.api.Plugin;
importcom.phonegap.api.PluginResult;
importcom.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
 *
 */
publicclassDirectoryListPluginextendsPlugin {
    /** List Action */
    publicstaticfinalString ACTION ="list";
 
 
    /*
     * (non-Javadoc)
     *
     * @see com.phonegap.api.Plugin#execute(java.lang.String,
     * org.json.JSONArray, java.lang.String)
     */
    @Override
    publicPluginResult 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(newFile(fileName));
                Log
                        .d("DirectoryListPlugin","Returning "
                                + fileInfo.toString());
                result =newPluginResult(Status.OK, fileInfo);
            }catch(JSONException jsonEx) {
                Log.d("DirectoryListPlugin","Got JSON Exception "
                        + jsonEx.getMessage());
                result =newPluginResult(Status.JSON_EXCEPTION);
            }
        }else{
            result =newPluginResult(Status.INVALID_ACTION);
            Log.d("DirectoryListPlugin","Invalid action : "+ action
                    +" passed");
        }
        returnresult;
    }
 
 
    /**
     * 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
     */
    privateJSONObject getDirectoryListing(File file)throwsJSONException {
        JSONObject fileInfo =newJSONObject();
        fileInfo.put("filename", file.getName());
        fileInfo.put("isdir", file.isDirectory());
        if(file.isDirectory()) {
            JSONArray children =newJSONArray();
            fileInfo.put("children", children);
            if(null!= file.listFiles()) {
                for(File child : file.listFiles()) {
                    children.put(getDirectoryListing(child));
                }
            }
        }
        returnfileInfo;
    }
}
5.將插件類導出成jar 包

Eclipse中以下操做: android

  • 在要生成jar的項目上右擊,選擇菜單上的Export(導出)
  • 導出類型選擇Jar File
  • 選擇或者輸入生成路徑
  • 選擇要導出的類
咱們導出成directorylist.jar

6.實現JavaScript插件

  • 建立一個名爲DirectoryListing的類
  • 建立一個成員函數list()
  • 在成員函數中調用PhoneGap.exec(<<successCallback>>,<<failureCallback>>,<<Plugin Name>>,<<Action Name>>,<<Arguments Array>>);
  • 將js文件保存爲directorylisting.js

代碼: json

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
 * 
 * @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) {
        returnPhoneGap.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
    }
};

3、測試 api

1.建立一個PhoneGap應用 http://www.phonegap.com/start/#android xcode

2.將 directorylisting.jar 加入工程依賴 ide

3.將directorylisting.js放入到 /assets/www 目錄下。 函數

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

?
1
2
<pluginname="DirectoryListPlugin"
    value="com.trial.phonegap.plugin.directorylisting.DirectoryListPlugin"/>

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

代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!DOCTYPE HTML>
<html>
     <head>
          <title>PhoneGap</title>
     </head>
     <body>
          <!-- Button -->
          <input disabled id="list-sdcard"type="button"value="List SDCard Contents" />
          <hr>
  
          <!-- Place Holderforplacing 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() {
   varbtn = document.getElementById("list-sdcard");
   btn.onclick =function() {
    DirectoryListing.list(   "/sdcard",
function(r){printResult(r)},
function(e){log(e)}
);
    }
    btn.disabled=false;
  },true);
  
  
 functionprintResult(fileInfo){
  varinnerHtmlText=getHtml(fileInfo);   
  document.getElementById("result").innerHTML=innerHtmlText;
 }
  
 functiongetHtml(fileInfo){
 varhtmlText="<ul><li>"+fileInfo.filename;
 if(fileInfo.children){
  
 for(varindex=0;index<fileInfo.children.length;index++){
 htmlText=htmlText+getHtml(fileInfo.children[index]);
 }
 }
 htmlText=htmlText+"</li></ul>";
 returnhtmlText;
  
 }
          </script>
  
     </body>
</html>

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

文章轉自 : http://blog.csdn.net/yyan/article/details/6664863

相關文章
相關標籤/搜索