Cordova插件开发

来源:互联网 发布:win7如何设置网络类型 编辑:程序博客网 时间:2024/05/01 16:05

一、在Cordova中,通过JS调用native的接口进行本地代码的调用和显示,进行Hybird,而这样的native的封装使用了plugin的方式。

二、这些plugin从cordova.js该文件中可窥端倪,诸如:

cordova.define('cordova/plugin_list', function(require, exports, module) {module.exports = [    {        "file": "plugins/org.apache.cordova.dialogs/www/notification.js",        "id": "org.apache.cordova.dialogs.notification",        "merges": [            "navigator.notification"        ]    },];    

这样的方式进行插件的声明。
并在编写的插件的js文件中进行调用java代码:

cordova.define("plugins.WebToast", function (require, exports, module) {    var exec = require('cordova/exec');    /**     * Provides access to notifications on the device.     */    module.exports = {        showToast: function (content, type) {            exec(null, null, "WebToast", "showToast", [content, type]);        }    }})

这里的exec即定义了在java中的showToast和参数等需要的东西。

三、自定义Toast的Cordova插件实现

3.1、在src目录下新建:plugins目录,用来存放cordova插件

在新建的你目录下,新建“WebToast.java”类,继承CordovaPlugin,覆写其中的execute方法:

public class WebToast extends CordovaPlugin {    @Override    public boolean execute(String action, JSONArray args,            CallbackContext callbackContext) throws JSONException {        if("showToast".equals(action)){            showToast(args.getString(0),args.getInt(1));        }        callbackContext.success();        return true;    }    private void showToast(String string, int type) {        if(type==1){            Toast.makeText(cordova.getActivity(), string, Toast.LENGTH_LONG).show();        }else{            Toast.makeText(cordova.getActivity(), string, Toast.LENGTH_SHORT).show();        }    }}

3.2、在Cordova_plugin.js中进行插件声明

{        "file": "plugins/webToast.js",        "id": "plugins.WebToast",        "merges": [            "navigator.webtoast"        ]    },

这里的声明表明你在js方法中使用

function show(text, type) {            navigator.webtoast.showToast(text, type);        }

这样的方式进行webToast.js中的showToast方法的调用。

3.3、在asserts/www下面建立“plugins”目录,并编写webToast.js文件

cordova.define("plugins.WebToast", function (require, exports, module) {    var exec = require('cordova/exec');    /**     * Provides access to notifications on the device.     */    module.exports = {        showToast: function (content, type) {            exec(null, null, "WebToast", "showToast", [content, type]);        }    }})

这里的showToast方法就是在js中被调用的方法,该方法执行了exec方法,exec方法详解:

exec(null, null, "WebToast", "showToast", [content, type]);

第一个参数:成功的回调;
第二个参数:错误的回调;
第三个参数:插件的名称(在res/xml/config.xml中进行声明);
第四个参数:执行的java中的方法名;
第五个参数:json形式的参数携带。

3.4、在res/xml/config.xml文件中进行声明

<feature name="WebToast">          <param name="android-package" value="plugins.WebToast"/>           </feature> 

其中feature的name是该插件的名称,params中value是插件类的”包名.类名”。

3.5、编写html文件进行js引用并调用本地Cordova插件

3.6、一个完整的项目结构

cordova_plugin

需要注意的地方就是要进行

<script type="text/javascript" src="cordova.js"></script><script type="text/javascript" src="plugins/webToast.js"></script>

的引用

0 0
原创粉丝点击