I am using ionic framework to make android app .I am having cordova 5.1 version .first I create a project using command line ionic start myApp tabs
Yes, custom cordova plugins are painful because the official docs are not so great.
First of all we need to understand a custom plugin folder structure.
In your android folder create a CustomPlugin.java file.
package com.example.myplugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
public class CustomPlugin extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if ("beep".equals(action)) {
// print your log here...
callbackContext.success();
return true;
}
return false; // Returning false results in a "MethodNotFound" error.
}
}
Now we need to build a interface between javascript and java code.
Cordova provides a simple function for this.
exec(, , , , []);
create a MycustomPlugin.js
file in www
folder.
cordova.exec( successCallback, ErrorCallBack, "service","action", []);
It is worth to know that,
service -> Name of the java class
action -> action we want to call ( in this case "beep" see above code)
Your MycustomPlugin.js file should look like this:
var MyPlugin = {
PrintLog: function (successCallback, errorCallback, action) {
cordova.exec(
successCallback, // success callback function
errorCallback, // error callback function
'CustomPlugin', // mapped to our native Java class called
action, // with this action name , in this case 'beep'
[] )// arguments, if needed
}
}
module.exports = MyPlugin;
Lastly you need to configure your plugin.xml
file
Cordova Plugin
now add this plugin to your project. myApp (the one you created)
using cordova plugin add /path/to/your/custom/plugin
And in $ionicPlatform.ready function call your java code from javascript
window.MycustomPlugin.PrintLog(function(res){
//success
}, function(err){
//error
}, "beep")