【Cordova】Cordova第一個插件的開發與使用
- Cordova插件開發
-
- 目标說明
- 首次嘗試
-
- 建立一個cordova項目
- 建立一個插件項目并編輯
- 為cordova項目添加插件
- 修改cordova項目代碼
- Build與運作
- 完成題目功能
-
- 修改插件
- 修改cordova項目
- 重新生成項目
- 成果
Cordova插件開發
目标說明
- 使用cordova實作一個小型電腦,能夠進行整數的加減乘除功能
- 将加減乘除的功能包裝成插件,cordova項目通過調用插件暴露的接口使用功能
- 計算通過Android原生代碼實作(也就是說計算功能放在java檔案中,js檔案通過cordova的exec子產品方法調用java代碼使用功能
首次嘗試
在正式開發之前,先建構一個基本架構,調用并了解預設代碼
注:在運作指令行之前,請确認你已經建構好了cordova + plugman環境,如果沒有,請執行以下指令行:(在任何目錄下均可)
$ npm install -g cordova
$ npm install -g plugman
目标:跑通第一個cordova + plugin項目,在index.html中添加按鈕,完成初始方法coolMethod的調用和簡單算數方法sum的調用
建立一個cordova項目
首先建立一個cordova項目
建立一個CordovaPlugin目錄作為根目錄,在根目錄中打開cmd,依次執行以下指令:
$ cordova create MyPlugTest2
$ cd MyPlugTest2
$ cordova platform add android
# 為了使得調試比較友善,可以添加browser平台
$ cordova platform add browser
需要注意:
- 新增的browser平台不能調用安卓的java代碼,也就是不能通過cordova的exec方法調用原生代碼。
- 添加browser平台是為了能夠及時通過網頁檢視并調試一些功能,避免每一次都需要cordova build android後再在Android Studio中檢視。
建立一個插件項目并編輯
下一步是建立一個插件項目
在CordovaPlugin檔案夾中,執行:
$ plugman create --name MyPlugin2 --plugin_id MyPlugin2 --plugin_version 0.1.0
$ cd MyPlugin2
$ plugman platform add --platform_name android
$ plugman createpackagejson ./
修改插件的js代碼:
// MyPlugin2/www/MyPlugin2.js
var exec = require('cordova/exec');
exports.coolMethod = function (arg0, success, error) {
exec(success, error, 'MyPlugin2', 'coolMethod', [arg0]);
};
exports.coolMethodSum = function(arg0, success, error){
exec(success, error, 'MyPlugin2', 'sum', arg0);
};
修改插件的android代碼:
// MyPlugin2\src\android\MyPlugin2.java:
package MyPlugin2;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* This class echoes a string called from JavaScript.
*/
public class MyPlugin2 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;
}
else if(action.equals("sum")){
callbackContext.success(args.getInt(0) + args.getInt(1));
return true;
}
return false;
}
private void coolMethod(String message, CallbackContext callbackContext) {
if (message != null && message.length() > 0) {
callbackContext.success(message);
} else {
callbackContext.error("Expected one non-empty string argument.");
}
}
}
儲存
為cordova項目添加插件
在MyPlugTest2目錄下執行:
$ cordova plugin add ./MyPlugin2
如果添加不成功,請将./MyPlugin2替換為MyPlugin2的絕對路徑
注:在這裡原本可以通過添加- -link參數建構Debug環境:
$ cordova plugin add ../path/to/my/plugin/relative/to/project --link
但是一直在報錯,懶得找原因,是以放棄
修改cordova項目代碼
修改index.html:
<!-- MyPlugTest2\www\index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">
<meta name="color-scheme" content="light dark">
<link rel="stylesheet" href="css/index.css">
<title>Hello World</title>
</head>
<body>
<div class="app">
<h1>Apache Cordova</h1>
<div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p>
<button onclick="coolMethod()">點選調用Cool</button>
<button onclick="coolMethodSum(2,3)">點選調用Sum</button>
</div>
</div>
<script src="cordova.js"></script>
<script src="js/index.js"></script>
</body>
</html>
注:在這裡我删去了自動生成代碼中的這一行:
這是因為如果添加了這一行,浏覽器會添加CSP安全标準,禁止兩個按鈕的功能調用,是以需要删去
修改index.js:
// MyPlugTest2\www\js\index.js
function success(msg){
alert(msg);
}
function error(msg){
alert(msg);
}
function coolMethod(){
cordova.plugins.MyPlugin2.coolMethod("cool", success, error);
alert("cool");
}
function coolMethodSum(x, y){
cordova.plugins.MyPlugin2.coolMethodSum([1, 2], success, error);
alert("sum");
}
Build與運作
在浏覽器中預覽(預覽,因為不能使用java的方法
在cordova項目的目錄下運作:
$ cordova build browser
$ cordova run browser
效果如下:
注意:因為不能使用java方法,是以第一個彈出框顯示為
Error:missing command error
這個是正常現象
建構安卓項目:
在cordova項目中運作:
$ cordova build android
# build之後可以直接在Android中打開MyPlugTest2\platforms\android\app
$ cordova run android
注:如果上面指令輸出了以下錯誤,請忽略,隻要確定出現了build success,就可以繼續進行下一步
下一步,在Android Studio中打開MyPlugTest2\platforms\android\app項目(請確定你的Android Studio環境已經正确配置,并添加了虛拟機),等待gradle編譯後即可運作如下(第一、第二個彈出框都有内容
完成題目功能
功能界面設計如下:
修改插件
由于之前為cordova項目添加插件的方式中,使用link參數添加失敗了,是以如果需要修改插件源代碼,首先需要删除項目中引入的插件
在cordova項目下執行以下指令:
$ cordova plugin remove MyPlugin2
下一步就可以修改MyPlugin2插件的源代碼了:
首先修改java源代碼,添加加減乘除的功能函數:
// MyPlugin2\src\android\MyPlugin2.java
package MyPlugin2;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MyPlugin2 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;
}
else if(action.equals("sum")){
callbackContext.success(args.getInt(0) + args.getInt(1));
return true;
}
else if(action.equals("minus")){
callbackContext.success(args.getInt(0) - args.getInt(1));
return true;
}
else if(action.equals("multiple")){
callbackContext.success(args.getInt(0) * args.getInt(1));
return true;
}
else if(action.equals("divide")){
callbackContext.success(args.getInt(0) / args.getInt(1));
return true;
}
return false;
}
private void coolMethod(String message, CallbackContext callbackContext) {
if (message != null && message.length() > 0) {
callbackContext.success(message);
} else {
callbackContext.error("Expected one non-empty string argument.");
}
}
}
然後修改JS代碼:
// MyPlugin2\www\MyPlugin2.js
var exec = require('cordova/exec');
exports.coolMethod = function (arg0, success, error) {
exec(success, error, 'MyPlugin2', 'coolMethod', [arg0]);
};
exports.coolMethodSum = function(arg0, success, error){
exec(success, error, 'MyPlugin2', 'sum', arg0);
};
exports.coolMethodMinus = function(arg0, success, error){
exec(success, error, 'MyPlugin2', 'minus', arg0);
};
exports.coolMethodMultiple = function(arg0, success, error){
exec(success, error, 'MyPlugin2', 'multiple', arg0);
};
exports.coolMethodDivide = function(arg0, success, error){
exec(success, error, 'MyPlugin2', 'divide', arg0);
};
修改cordova項目
首先需要重新引入修改後的插件:
在MyPlugTest2目錄下執行:
$ cordova plugin add ./MyPlugin2
如果添加不成功,将./MyPlugin2替換為MyPlugin2的絕對路徑
修改index.html:
<!-- MyPlugTest2\www\index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">
<meta name="color-scheme" content="light dark">
<link rel="stylesheet" href="css/index.css">
<title>Hello World</title>
</head>
<body>
<div class="app">
<h1>Apache Cordova</h1>
<div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p>
<button onclick="coolMethod()">點選調用Cool</button>
<button onclick="coolMethodSum(2,3)">點選調用Sum</button>
</div>
<div>
<label for="input1">參數1</label>
<input type="text" id="input1"/>
<br/>
<label for="input2">參數2</label>
<input type="text" id="input2"/>
<div>
<button id="sumbtn" onclick="coolMethodSum()">+</button>
<button id="minusbtn" onclick="coolMethodMinus()">-</button>
<button id="multiplebtn" onclick="coolMethodMultiple()">*</button>
<button id="dividebtn" onclick="coolMethodDivide()">/</button>
</div>
<label for="input2">計算結果</label>
<input type="text" id="calcresult"/ disabled>
</div>
</div>
<script src="cordova.js"></script>
<script src="js/index.js"></script>
</body>
</html>
修改index.js
// MyPlugTest2\www\js\index.js
function success(msg){
alert(msg);
document.getElementById("calcresult").value = msg;
}
function error(msg){
alert(msg);
}
function coolMethod(){
cordova.plugins.MyPlugin2.coolMethod("cool", success, error);
alert("cool");
}
function coolMethodSum(){
x = document.getElementById("input1").value;
y = document.getElementById("input2").value;
cordova.plugins.MyPlugin2.coolMethodSum([x, y], success, error);
alert("sum");
}
function coolMethodMinus(){
x = document.getElementById("input1").value;
y = document.getElementById("input2").value;
cordova.plugins.MyPlugin2.coolMethodMinus([x, y], success, error);
alert("minus");
}
function coolMethodMultiple(){
x = document.getElementById("input1").value;
y = document.getElementById("input2").value;
cordova.plugins.MyPlugin2.coolMethodMultiple([x, y], success, error);
alert("multiple");
}
function coolMethodDivide(){
x = document.getElementById("input1").value;
y = document.getElementById("input2").value;
cordova.plugins.MyPlugin2.coolMethodDivide([x, y], success, error);
alert("divide");
}
重新生成項目
在cordova項目中運作:
$ cordova build android
# build之後可以直接在Android中打開MyPlugTest2\platforms\android\app
$ cordova run android
成果
在Android Studio中打開MyPlugTest2\platforms\android\app檔案夾,可以調試項目,最終成果如下:
參考:
Cordova插件開發一篇就夠了
Cordova插件使用和開發學習筆記
使用plugman 建立一個自己的cordova插件
附件
源代碼