ionic之cordova外掛自定義
阿新 • • 發佈:2019-02-10
外掛檔案目錄
外掛java類
package com.cool.toast;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Intent;
import android.widget.Toast;
public class ShowToast extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
// TODO Auto-generated method stub
if("showToast".equals(action)){
Toast.makeText(cordova.getActivity(), "show...", Toast.LENGTH_SHORT).show();
callbackContext.success("success");
return true ;
}
callbackContext.error("error");
return false;
}
}
外掛js程式碼
var exec = require('cordova/exec');
var myFunc = function(){};
// arg1:成功回撥
// arg2:失敗回撥
// arg3:將要呼叫類配置的標識
// arg4:呼叫的原生方法名
// arg5:引數,json格式
myFunc.prototype.showToast=function(success, error) {
exec(success, error, "CoolToast", "showToast" , []);
};
var showt = new myFunc();
module.exports = showt;
外掛plugin程式碼
<?xml version='1.0' encoding='utf-8'?>
<plugin id="coolPlugin" version="0.0.1" xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android">
<name>CoolPlugin</name>
<js-module name="CoolPlugin" src="www/CoolPlugin.js">
<clobbers target="cool.toast" />
</js-module>
<!-- android -->
<platform name="android">
<config-file target="res/xml/config.xml" parent="/*">
<feature name="CoolToast">
<param name="android-package" value="com.cool.toast.ShowToast"/>
</feature>
</config-file>
<source-file src="src/android/ShowToast.java" target-dir="src/com/cool/toast" />
<config-file target="AndroidManifest.xml" parent="/*">
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
</config-file>
</platform>
</plugin>
外掛打包
使用命令:ionic plugin add 外掛目錄 ##E:\Coolplugin
外掛呼叫
因為測試使用的是ionic的程式碼,所以在run方法裡面增加了外掛測試呼叫
.run(function ($ionicPlatform) {
$ionicPlatform.ready(function () {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
//alert("$ionicPlatform.ready");
cool.toast.showToast();//呼叫外掛
});
})
打包apk
ionic build android
測試效果
感謝兩位大神的無私分享: