做这个功能的前提条件是要有ionic和android的基础的,相关的建文件环境不再描述;
1、www文件中的配置
1.1 、cordova_plugins.js 和 intent.js的对应配置
ordova_plugins.js中配置的数据是Controller中的调用的前缀和调用的方法;
file: 是ionic中自定义插件的JS的位置;
id: intent.js中自定义插件的名字;
merges: js和Controller中调用的前缀,相当于console.log();中的console一样;
module.exports.metadata: 配置的是各个插件的版本,自定义的版本号自己配置;
cordova_plugins.js: 这个文件如下,主要是插件的列表和配置
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
{
"file": "plugins/cordova-plugin-whitelist/whitelist.js",
"id": "cordova-plugin-whitelist.whitelist",
"runs": true
},
{
"file": "plugins/cordova-plugin-themeablebrowser/www/themeablebrowser.js",
"id": "cordova-plugin-themeablebrowser.themeablebrowser",
"clobbers": [
"cordova.ThemeableBrowser"
]
},
{
"file": "plugins/intent.js",
"id": "org.apache.cordova.intent",
"merges": [
"navigator.intent"
]
}
];
module.exports.metadata =
// TOP OF METADATA
{
"cordova-plugin-whitelist": "1.2.1",
"cordova-plugin-themeablebrowser": "0.2.15",
"org.apache.cordova.intent" :"1.0.1",
};
// BOTTOM OF METADATA
});
plugins/intent.js配置,项目初始可能没有这个文件,作者自己新建。
JavaScript 的中声明的 exec函数是调用到android上插件的execute 方法;
/** * Created by Administrator on 2016/4/23. */ cordova.define("org.apache.cordova.intent", function(require, exports, module) {
var exec = require('cordova/exec');
module.exports = {
/** * 一共5个参数 第一个 :成功回调 mills:android 返回的数据,是类中callbackContext.success传递的参数 第二个 :失败回调 errorParam:android 返回的数据,是类中callbackContext.error传递的参数 第三个 :调用的是android中类的配置名字(在xml/config.xml中配置,下面会讲解) 第四个 :调用的方法名(一个类里可能有多个方法 靠这个参数区分) 第五个 :传递的参数 以json的格式 */
toastShow: function(mills) {
exec(function(winParam){
alert(winParam);
},function (errorParam) {
alert(errorParam);
}, "DivPlugin", "toastShow", [mills]);
},
}; });
1.2、 JS 和Controller中调用实施
Controller的配置中的调用:
angular.module('home.ctrl', [])
.controller('homeCtrl', function ($scope,$state,$log,HomeFactory,$ionicSlideBoxDelegate,$ionicScrollDelegate) {
$scope.hometitle='首页';
......
$scope.toastShow=function () {
navigator.intent.toastShow('js To Android 数据');
};
});
2、android 方面的配置
android 方向的主要的配置工作是建立自定义组件的类继承CordovaPlugin,然后配置识别接受的类和方法;
2.1、xml/config.xml 的配置
feature name:要与1.1中的plugins/intent.js配置第三个参数相对应;
value:android方面的自定义插件的路径和类名;
......
name="android-package"
value="com.***.overseas.DivPlugin" />
2.2、android自定义插件的类名
主要的两个点:
1、类名同2.1的指定类路径名;
2、action的名字1.1中的plugins/intent.js配置第四个参数相对应;
public class DivPlugin extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
//匹配的是方法的名字
if (action.equals("toastShow")) {
String message = args.getString(0);
Toast.makeText(cordova.getActivity(),message, Toast.LENGTH_LONG).show();
return true;
}
return false;
}
}
总结:以上就是配置Cordova和andorid交互的自定义组件的过程;如有遇到其他问题,请留言;