Android Cordova 外掛程式開發之編寫自己定義外掛程式

來源:互聯網
上載者:User

標籤:ica   名稱   encoding   get   cer   sage   odi   rgs   lis   

前言

本文適合Android+web的複合型人才,由於cordova本身就是混合開發,所以在Android開發的基礎上,還要懂web相關技術(HTML+CSS+JS)。可是也有例外,比方我。僅僅需負責Android方面。web方面的交由其它web組人員開發。儘管。web略懂一點。但我主要還是搞Android開發的。

編寫自己定義外掛程式類

本節的內容是。自己定義一個dialog外掛程式。供web調用,顯示系統彈窗。
建立一個包名,我這裡使用org.apache.cordova.dialog。然後建立個類CustomDialog.java。繼承於CordovaPlugin(全部自己定義外掛程式,都要繼承CordovaPlugin),最後重寫execute方法。


execute有三個重載方法:

public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext)
public boolean execute(String action, String rawArgs, CallbackContext callbackContext)

這三個方法。假設你看了CordovaPlugin原始碼的話。會發現,事實上最後都調用了第二個方法,可是CordovaArgs僅僅是對JSONArray的一個封裝。方便操作json資料而已,所以要重寫哪個。按個人喜好。

這裡。我是重寫了第二個方法,如今來說明下方法參數:
String action:一個類裡面能夠提供多個功能,action就是指名了要調用哪個功能。
CordovaArgs args:web以json的資料格式傳遞給Android native。CordovaArgs 是對JSONArray 的一個封裝。
CallbackContext callbackContext:這個是回調給web,有success和error兩種回調方法。

詳細實現例如以下:

public class CustomDialog extends CordovaPlugin{    @Override    public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {        if("show".equals(action)){            AlertDialog.Builder builder = new AlertDialog.Builder(cordova.getActivity());            builder.setTitle("提示");            builder.setMessage(args.getString(0));            builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {                @Override                public void onClick(DialogInterface dialog, int which) {                    dialog.dismiss();                    callbackContext.success("點擊了確定");                }            });            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {                @Override                public void onClick(DialogInterface dialog, int which) {                    dialog.dismiss();                    callbackContext.error("點擊了取消");                }            });            builder.create().show();            return true;        }        return super.execute(action, args, callbackContext);    }}

假設web使用了CustomDialog外掛程式。並調用show方法(action)。這時候,會彈出一個系統表單。會顯示web傳過來的訊息內容,點擊確定,回調web,告訴它調用成功,取消則是失敗。最後記得return true(表示調用成功)。

配置config.xml

開啟res/xml/config.xml檔案,原本內容例如以下:

<?xml version=‘1.0‘ encoding=‘utf-8‘?><widget id="com.example.helloworld" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">    <preference name="loglevel" value="DEBUG" />    <feature name="Whitelist">        <param name="android-package" value="org.apache.cordova.whitelist.WhitelistPlugin" />        <param name="onload" value="true" />    </feature>    <allow-intent href="market:*" />    <name>HelloWorld</name>    <description>        A sample Apache Cordova application that responds to the deviceready event.    </description>    <author email="[email protected]" href="http://cordova.io">        Apache Cordova Team    </author>    <content src="index.html" />    <access origin="*" />    <allow-intent href="http://*/*" />    <allow-intent href="https://*/*" />    <allow-intent href="tel:*" />    <allow-intent href="sms:*" />    <allow-intent href="mailto:*" />    <allow-intent href="geo:*" /></widget>

Whitelist是基礎項目內建的一個外掛程式,相同的,我們在widget節點下也加入一個feature。

<?

xml version=‘1.0‘ encoding=‘utf-8‘?><widget id="com.example.helloworld" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0"> <preference name="loglevel" value="DEBUG" /> <feature name="Whitelist"> <param name="android-package" value="org.apache.cordova.whitelist.WhitelistPlugin" /> <param name="onload" value="true" /> </feature> <!--彈窗外掛程式--> <feature name="CustomDialog"> <param name="android-package" value="org.apache.cordova.dialog.CustomDialog" /> </feature> <allow-intent href="market:*" /> <name>HelloWorld</name> <description> A sample Apache Cordova application that responds to the deviceready event. </description> <author email="[email protected]" href="http://cordova.io"> Apache Cordova Team </author> <content src="index.html" /> <access origin="*" /> <allow-intent href="http://*/*" /> <allow-intent href="https://*/*" /> <allow-intent href="tel:*" /> <allow-intent href="sms:*" /> <allow-intent href="mailto:*" /> <allow-intent href="geo:*" /></widget>

feature name能夠隨便取,param value填的是詳細類的位置。

web配置並調用1、配置

開啟asserts/www/cordova_plugins.js檔案,注冊外掛程式。

cordova.define(‘cordova/plugin_list‘, function(require, exports, module) {module.exports = [    {        "file": "plugins/cordova-plugin-whitelist/whitelist.js",        "id": "cordova-plugin-whitelist.whitelist",        "runs": true    },    {        "file": "plugins/cordova-plugin-dialog/dialog.js",//js檔案路徑        "id": "cordova-plugin-dialog.CustomDialog",//js cordova.define的id        "clobbers": [            "alertDialog"//js 調用時的方法名        ]    }];module.exports.metadata = // TOP OF METADATA{    "cordova-plugin-whitelist": "1.2.1"};// BOTTOM OF METADATA});

然後在assets/www下建立dialog.js檔案

內容例如以下:

cordova.define("cordova-plugin-dialog.CustomDialog",    function(require, exports, module) {        var exec = require("cordova/exec");        module.exports = {            show: function(content){                exec(                function(message){//成功回調function                    console.log(message);                },                function(message){//失敗回調function                    console.log(message);                },                "CustomDialog",//feature name                "show",//action                [content]//要傳遞的參數。json格式                );            }        }});

cordova.define 的第一個參數就是cordova_plugins.js裡面定義的id,最基本的是exec方法,參數說明:
參數1:成功回調function
參數2:失敗回調function
參數3:feature name,與config.xml中注冊的一致
參數4:調用java類時的action
參數5:要傳遞的參數,json格式

2、調用

配置完上面的。僅僅剩下在合適的地方調用它了。
開啟assets/www/js/index.js
找到onDeviceReady方法,然後調用

alertDialog.show(‘Hello World!!!!‘);

這裡直接調用alertDialog,就是在cordova_plugins.js下定義的clobbers名稱,show是在js申明的function
index.js#onDeviceReady

onDeviceReady: function() {        app.receivedEvent(‘deviceready‘);        //調用自己定義外掛程式        alertDialog.show(‘Hello World!!!!‘);    }

直接在Android Studio運行,例如以下:

這個對話方塊就是Android 系統的AlertDialog。

當我們點擊確定時。就會回調js success function,列印出日誌。

不要運行cordova build命令。!


須要注意的是。假設你上一篇章有細緻看過之後,你會有這麼個疑問,編譯項目不是用

cordova build

命令的嗎?非常好,網上非常多說。在項目中。代碼都已經寫好了。可是一運行該命令,不但沒有生效,反而之前寫的外掛程式代碼都沒了。事實上,假設你知道整個項目編譯過程。那麼問題就迎刃而解了。

這裡簡單的說下。看的目錄結構

plugins是存放外掛程式的目錄。而www是存放H5項目的。也就是Android項目下的asserts/www下的檔案,當運行cordova build時,它會依據config.xml配置來編譯項目,然後會將plugins和www下的檔案應用到platforms目錄下的各個平台,這就是“一次編譯,多平台運行”。

可是。至始至終,我們編寫的代碼都是在Android平台下的。而上面提到的兩個目錄我們都沒有動過。也就是說,全部配置都沒有動過。都是初始狀態,所以運行build後也就沒有效果。

總結

通過上面的執行個體,已經實現了簡單的自己定義外掛程式,可是它僅僅是在Android平台上實現的。那麼。我們怎麼應用在其它的平台上呢?或者說,我們實現一個外掛程式之後,怎麼提供給別人項目使用呢?下一節,將說說外掛程式安裝包怎樣產生。就是解決這幾個問題的。

原始碼

Android Cordova 外掛程式開發之編寫自己定義外掛程式

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.