如何為Ionic添加plugin

一、新建cordova plugin項(xiàng)目,項(xiàng)目工程結(jié)構(gòu)如下所示,主要包括三個(gè)文件: src、www和plugin.xml。

cordova 工程結(jié)構(gòu)

1、src文件主要編寫不同平臺(tái)下的native代碼。Eg: android 和ios

/**
新建的類一定要繼承自CordovaPlugin類,并重寫execute方法
**/
public class LoadingPlugin extends CordovaPlugin {

    public ProgressDialog loadingDialog;
    public LayoutInflater inflater;
    public AlertDialog.Builder alertDialogBuilder;
    public AlertDialog alertDialog;
    private Handler handler = new Handler();
    private TextView text ;

    @Override
    public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {

        if ("showLoading".equals(action)) {
            this.createDialog(cordova.getActivity(), "loading...");
            callbackContext.success("showLoading success!");
            return true;
        } else if("dismissDialog".equals(action)) {
          this.dismissDialog();
          callbackContext.success("dismissDialog success!");
          return true;
        } else {
          callbackContext.error("get plugin error!");
          return false;
        }
    }
}

2、www文件中提供調(diào)用native代碼的接口,以供JavaScript代碼調(diào)用

var exec = require('cordova/exec');
exports.showLoading = function(msg, success, error) {
//五個(gè)參數(shù):成功的回調(diào)方法、失敗的回調(diào)方法、service、action、傳遞的參數(shù)
exec(success, error, "LoadingPlugin", "showLoading", [msg]);
}

3、plugin.xml文件主要作用是處理js文件與Android、ios等平臺(tái)的相關(guān)配置

<?xml version='1.0' encoding='utf-8'?>
<plugin id="expense-plugin-loading" version="0.0.1" xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android">
    <name>LoadingPlugin</name>
    <!-- js-module標(biāo)簽:和Java文件交互的js文件。屬性src就是www下面的js文件-->
    <js-module name="LoadingPlugin" src="www/LoadingPlugin.js"><clobbers target="loadingManager"/></js-module>

    <!--platform標(biāo)簽:為plugin添加的平臺(tái),本文主要是開發(fā)Android平臺(tái)上的代碼-->
    <platform name="android">
      <!--config-file標(biāo)簽:將配置文件注入到Android工程中的config.xml中-->
        <config-file parent="/*" target="res/xml/config.xml">
            <feature name="LoadingPlugin">
            <param name="android-package" value="com.baiwangmaoyi.expense.LoadingPlugin"/>
            </feature>
        </config-file>
        <config-file parent="/*" target="AndroidManifest.xml">
        </config-file>
        <!--srource-file標(biāo)簽:將src下的文件復(fù)制到platform下相應(yīng)的工程目錄下-->
        <source-file src="src/android/LoadingPlugin.java" target-dir="src/com/baiwangmaoyi/expense"/>
        <source-file src="src/android/layout/loading_layout.xml" target-dir="res/layout" />
      </platform>
</plugin>

二、為Ionic添加所寫的Plugin

1、 cordova plugin add [path to your plugin]

2、編寫調(diào)用native文件的js代碼并將其封裝為.ts

文件名:ShowLoading.js

'use strict';
var {Observable} = require('rxjs/Rx');
var ShowLoading = (function(){
    function ShowLoading(){};
    ShowLoading.prototype.showLoading = function(msg){
        var promise = new Promise(function(resolve, reject){
            /**loadingManager是add plugin 時(shí)系統(tǒng)根據(jù)js-module中clobbers中設(shè)置的
             ** target值而生成的全局變量
             **showLoading為plugin工程中www下的.js文件中導(dǎo)出的方法名 **/
            loadingManager.showLoading(msg, function(data){
                resolve(data);
            }, function(err){
                reject(err);
            });
            // resolve("success");
        });
        return promise;
    };
    ShowLoading.prototype.dismissLoading = function(msg){
        var promise = new Promise(function(resolve, reject){
            loadingManager.dismissLoading('', function(data){
                resolve(data);   
            }, function(err){
                resolve(err);
            });
            // resolve("success");
        });
        return promise;
    };
    return ShowLoading;
    
}());

exports.ShowLoading = ShowLoading;

文件名:ShowLoading.d.ts, 封裝后的方法。

export declare class ShowLoading {
    showLoading(msg: string): Promise<any>;
    dismissLoading(msg: string): Promise<any>;
}

三、在Ionic中.ts 文件中使用封裝后的方法:

 this.showLoading = new ShowLoading();
    this.showLoading.showLoading("loading").then(res => {
      this.showToast(res);
      console.log('success');
    }, err => {
      console.log('err',err);
      this.showToast(err);
    });

    setTimeout(() => {
      this.showLoading.dismissLoading('').then(res =>{
        this.showToast(res);
        console.log("dismiss",res);
      }, err => {
        this.showToast(err);
        console.log('dismiss',err);
      });
    },3000);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容