开发Cordova Plugin的时候,在Native Code里使用第三方Library,除了能够加速项目的时程、也避免了重复发明轮子的窘境。本篇文章介绍如何在Cordova的Plugin里使用Android Library,主要为本身留个纪录,也但愿能帮助到有须要的开发人员。javascript
参考数据:java
Android中的第三方Library,除了能够从网络上取得以外,也能够依照下列文章的步骤,创建一个本身的Android Library:「mylibrary.jar」。后续步骤,会拿这个mylibrary.jar作为第三方Library来使用。android
接着要动手撰写Cordova Plugin来使用Android Library,开发人员能够依照下列文章的步骤,创建一个本身的Cordova Plugin:「clk-cordova-sample」。后续步骤,会拿这个clk-cordova-sample作为Plugin主体来使用。git
完成上列两个步骤以后,开发人员会拥有Cordova Plugin:「clk-cordova-sample」、以及Android Library:「mylibrary.jar」。接着将mylibrary.jar放到clk-cordova-sample的src\android文件夹里,而且修改clk-cordova-sample的plugin.xml,定义Cordova编译的时候,将mylibrary.jar加入到平台项目的文件夹来进行编译。github
加入mylibrary.jarapache
<source-file src="src/android/mylibrary.jar" target-dir="libs" />
完整plugin.xmljson
<?xml version="1.0" encoding="UTF-8"?> <plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" id="clk-cordova-sample" version="1.0.0"> <!-- metadata --> <name>CLK Cordova Sample</name> <description>CLK Cordova Sample的说明</description> <license>Apache 2.0</license> <!-- javascript --> <js-module name="NotificationService" src="www/clk.cordova.sample.NotificationService.js" > <clobbers target="clk.cordova.sample.NotificationService" /> </js-module> <!-- android --> <platform name="android"> <!-- config --> <config-file target="res/xml/config.xml" parent="/*"> <feature name="NotificationService"> <param name="android-package" value="com.clk.cordova.sample.NotificationService"/> </feature> </config-file> <!-- source --> <source-file src="src/android/NotificationService.java" target-dir="src/com/clk/cordova/sample/NotificationService" /> <source-file src="src/android/mylibrary.jar" target-dir="libs" /> </platform> </plugin>
完成上列步骤后,接着动手修改clk-cordova-sample里NotificationService.java,来使用mylibrary.jar里面所提供的Class。网络
NotificationService.javapost
package com.clk.cordova.sample; import org.apache.cordova.*; import org.json.*; import android.widget.Toast; import myLibrary.MyClass; public class NotificationService extends CordovaPlugin { // methods public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { // show if(action.equals("show")) { // test MyClass x = new MyClass(); String message = "Hi " + x.getMessage(); // execute Toast.makeText(this.cordova.getActivity(), message, Toast.LENGTH_LONG).show(); // return return true; } // default return false; } }
最后,执行clk-cordova-sample里的范例APP。就能够在执行画面上,看到一个Toast窗口显示从Library取得的讯息内容,这也就完成了Cordova Plugin使用Android Library的相关开发步骤。this
显示回传讯息
范例程序代码:下载地址