Cordova插件开发(iOS/Android)--看这篇就够了

其他Cordova相关文章链接

- Cordova-现有iOS工程中集成Cordova
- Cordova-在现有iOS工程自动化接入Cordova插件(cordova机制原理)
- Cordova-源码分析

1.创建一个测试工程

//创建cordova工程
cordova create cordovaTest com.szcomtop.cordovaTest cordovaTest

//进入工程根目录
cd platforms

//添加iOS 和 Android 平台代码
cordova platform add ios 
cordova platform add android

2.创建插件

//安装插件工具 
npm install -g plugman

/**创建一个 弹出alert的插件
	name:插件名称
	plugin_id:插件id
	plugin_version:插件版本
**/

plugman create --name mytoast --plugin_id com.example.mytoast --plugin_version 0.0.1

执行完之后会看见一个mytoast文件夹在根目录下的plugins目录里面。把文件夹名称改成com.example.mytoast

2.1 生成package.json文件

//进入到插件目录
cd plugins/mytoast
//执行创建package.json文件
plugman createpackagejson ./

按照默认的选项提示创建即可

2.2 创建iOS/Android原生代码

  • iOS代码 — AlertPlugin.h 文件

    #import <Foundation/Foundation.h>
    #import <Cordova/CDVPlugin.h>
    NS_ASSUME_NONNULL_BEGIN
    
    @interface AlertPlugin : CDVPlugin
    //接收cordova消息方法
    - (void)coolMethod:(CDVInvokedUrlCommand*)command;
    
    @end
    
    NS_ASSUME_NONNULL_END
    
  • iOS代码 — AlertPlugin.m 文件

    #import "AlertPlugin.h"
    
      @implementation AlertPlugin
      - (void)coolMethod:(CDVInvokedUrlCommand*)command{
      //    NSLog(@"className:%@ - callbackId:%@ - args:%@ - methodName:%@",
      //          command.className,command.callbackId,command.arguments,command.methodName);
          
          if (command.arguments.count > 0) {
              UIAlertController *alertCtr = [UIAlertController alertControllerWithTitle:@"显示的标题" message:command.arguments[0] preferredStyle:UIAlertControllerStyleAlert];
              
              UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:(UIAlertActionStyle)UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                  CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"OC回传给js的参数"];
                  [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
              }];
              [alertCtr addAction:okAction];
              
              [[UIApplication sharedApplication].windows.firstObject.rootViewController presentViewController:alertCtr animated:YES completion:^{
                  
              }];
          }else{
              CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"没有参数"];
              [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
          }
          
      }
    
      @end
    
  • Android代码 — mytoast.java

    package com.example.mytoast;
    
    import org.apache.cordova.CordovaPlugin;
    import org.apache.cordova.CallbackContext;
    
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    //导包
    import android.widget.Toast;
    
    public class mytoast extends CordovaPlugin {
    
        @Override
        public boolean execute(String action, JSONArray args, CallbackContext   callbackContext) throws JSONException {
            if (action.equals("coolMethod")) {
                String message = args.getString(0);
                this.coolMethod(message, callbackContext);
                return true;
            }
            return false;
        }
    
        private void coolMethod(String message, CallbackContext     callbackContext) {
            if (message != null && message.length() > 0) {
                callbackContext.success(message);
                //吐司内容
                Toast.makeText(cordova.getContext(),message, Toast.LENGTH_LONG) .show();
            } else {
                callbackContext.error("Expected one non-empty string argument.  ");
            }
        }
    }
    

2.3 修改plugin.xml,添加iOS和Android平台相关字段

<?xml version='1.0' encoding='utf-8'?>
<plugin id="com.example.mytoast" version="0.0.1" xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android">
    <name>mytoast</name>
    <js-module name="mytoast" src="www/mytoast.js">
        <clobbers target="cordova.plugins.mytoast" />
    </js-module>
    
    <platform name="ios">
        <source-file src="src/ios/AlertPlugin.m" />
        <header-file src="src/ios/AlertPlugin.h" />
        
        <config-file target="config.xml" parent="/widget">
            
            <feature name="mytoast">
                <param name="ios-package" value="AlertPlugin" />
            </feature>
        </config-file>
    </platform>
    
    
    <platform name="android">
        <config-file parent="/*" target="res/xml/config.xml">
            <feature name="mytoast">
                <param name="android-package" value="com.example.mytoast.mytoast"/>
            </feature>
        </config-file>
        <config-file parent="/*" target="AndroidManifest.xml"></config-file>
        <source-file src="src/android/mytoast.java" target-dir="src/com/example/mytoast/mytoast"/>
    </platform>
</plugin>

2.4 插件js文件

var exec = require('cordova/exec');

exports.coolMethod = function (arg0, success, error) {
    exec(success, error, 'mytoast', 'coolMethod', [arg0]);
};

2.5 插件最终的目录结构

com.example.mytoast
         |-- package.json
         |-- plugin.xml
         |-- src
              |-- ios
                    |-- AlertPlugin.h
                    |-- AlertPlugin.m
              |-- android
                    |-- mytoast.java
         |-- www
              |-- mytoast.js

按照上面的目录结构,把原生文件放到对应的位置。

3. 测试插件

3.1 执行cordova命令添加插件

//add 后面参数为 我们新创建的插件文件夹
cordova plugin add ./plugins/com.example.mytoast

3.2 编写测试index.html

<!DOCTYPE html>
<html>
    <head>
        <title>TestPlugin</title>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8">
            <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
            <script type="text/javascript" charset="utf-8">

            function testPlugin() {
                cordova.plugins.mytoast.coolMethod("我是JS传来的参数!",alertSuccess,alertFail);
            }

            function alertSuccess(msg) {
                alert(msg);
            }

            function alertFail(msg) {
                alert('调用OC失败: ' + msg);
            }
            </script>
    </head>

    <body style="padding-top:50px">
        <button style="font-size:17px;" onclick="testPlugin();">调用iOS插件</button> <br>
    </body>
</html>

3.3 执行效果

Demo插件附件

插件Demo下载

官网参考地址

cordova的plugin.xml字段说明

posted @ 2020-05-28 17:46  iOS小熊  阅读(1700)  评论(0编辑  收藏  举报