自定义cordova插件(phonegap、ionic)

在开发cordova(phonegap、ionic)应用时,很多情况下需要用到一些h5无法实现的原生功能,这时候就需要用到插件。
在cordova的plugin库中已经有很多已经编写好的插件,可以登录官网cordova官网搜索,然后使用

cordova plugin add cordova-plugin-xxx

在项目中添加插件使用。但是有些时候我们需要的功能网上并没有现成插件、或者是我们自己所实现的原生功能,这时候我们就需要自己编写插件。整个过程可以参照现有的Apache组织编写的插件,如cordova-plugin-device等。

这里编写了一个cordova-plugin-mjtest插件,使用原生方法在控制台打印出前台传入的name的值。
这里所有操作在platform下的ios/android下完成

第一步编写js文件(mjtest.js)

在h5应用中,界面所调用的语言首先是js,这里是定义一些在应用中需要用到js方法。

cordova.define("cordova-plugin-mjtest.mjtest", function(require, exports, module) {
  var exec = require('cordova/exec');

  var mjtest = {
    test : function (args,successCallback,errorCallback){
      cordova.exec(successCallback,errorCallback,"Mjtest","test",args);
    }
  };
  module.exports = mjtest;
});

建立文件夹取名cordova-plugin-mjtest放在www的plugins下(名字随意取)

第二步配置cordova_plugins.js

在原有插件配置下添加:

{
        "file": "plugins/cordova-plugin-mjtest/www/mjtest.js",
        "id": "cordova-plugin-mjtest.mjtest",
        "pluginId": "cordova-plugin-mjtest",
        "clobbers": [
            "window.plugins.mjtest"
        ]
    }

第三步修改config.xml

iOS下:

<feature name="Mjtest">
        <param name="ios-package" value="Mjtest" />
    </feature>

android下:

<feature name="Mjtest">
        <param name="android-package" value="org.apache.cordova.mjtest.Mjtest" />
    </feature>

第四步编写原生代码

这里首先要会基本的android或者oc语法,swift暂时未尝试不知道是否有兼容问题。
具体的详细方法在cordova官网中有,如需要可以去查看,下面是我的代码:

android:

package org.apache.cordova.mjtest;


import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;


/**
 * Created by maxbalance on 12/21/15.
 */
public class Mjtest extends CordovaPlugin{

    /**
     * Sets the context of the Command. This can then be used to do things like
     * get file paths associated with the Activity.
     *
     * @param cordova The context of the main Activity.
     * @param webView The CordovaWebView Cordova is running in.
     */
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);
    }

    /**
     * Executes the request and returns PluginResult.
     *
     * @param action            The action to execute.
     * @param args              JSONArry of arguments for the plugin.
     * @param callbackContext   The callback id used when calling back into JavaScript.
     * @return                  True if the action was valid, false if not.
     */
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        //test
        if ("test".equals(action)) {
            final JSONObject options = args.getJSONObject(0);

            System.out.println(options.getString("name"));
            callbackContext.success(options.getString("name"));
        }
        return true;
    }
}

其中主要的方法为initialize与execute,第一个是定义,基本不许要修改,第二个方法是控制逻辑的。callbackContext是回调方法,是通信的关键,上面是成功回调,如果失败回调的话调用callbackContext.success即可。

iOS:

Mjtest.h

#import <Foundation/Foundation.h>
#import <Cordova/CDV.h>

@interface Mjtest :  CDVPlugin

- (void)test:(CDVInvokedUrlCommand*)command;

@end

Mjtest.m

#import "Mjtest.h"
#import <Cordova/CDV.h>

@implementation Mjtest

#pragma mark test
- (void)test:(CDVInvokedUrlCommand*)command {
    NSDictionary* options = [command.arguments objectAtIndex:0];
    //test
    NSString *name  = [options objectForKey:@"name"];
    NSLog(@"%@",name);
    CDVPluginResult * pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:name];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

@end

同样这里ios是成功回调,失败回调为:

    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorRes];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];

errorRes为错误的NSString

调用插件

在配置config.xml中我们定义了一个参数为

"clobbers": ["window.plugins.mjtest"]

这个一般以cordova开头,尽量不要起单个单词。
而window.plugins.mjtest这个就是js中调用的函数,而mjtest.js中定义的方法(test)就由这个方法函数调用。

if(window.cordova){
    window.plugins.mjtest.test([{'name':'mj'}],function(data){consoloe.log(data)});
}

这个在浏览器中无法运行,使用前请判断cordova

使用xcode/android studio运行,就可以在控制台查看效果了,或者可以在回调中获取回调数据。

因为过程比较长,所以写的比较省略,主要以代码为主。而且这种插件只能自己使用,无法做成统一插件,下一篇会介绍如何把插件做成和cordova-plugin-device一样可供下载安装的插件(同时也会少些一些代码)。

代码地址:https://github.com/MaxBalance/cordova-plugin-mjtest

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值