Preparation
- Install cordova
npm install -g cordova
- Create cordova project and add android platform
cordova create Project name Package name
cd Project name
cordova platform add android
- Install plugman
npm install -g plugman
Create plugin
- Create a plug-in (this blog demo plug-in name mytoast, package name com.digichain.mytoast)
plugman create --name plug-in name -- plugin UU ID plug-in ID -- plugin UU version plug-in version //Plug in id, such as com.digichain.xin //Plug in version, such as 1.0.0
- plugin.xml
plugin{
id: "Plug-in unit id",
version: "Plugin version",
name: "Plug-in name",
js-module: {
name: "Module name",
src: "js File address",
clobbers: {
target: "H5 Call middleware method"
}
},
platform: {
source-file: {
src: "Class name",
target-dir:"Plug in files copied to the location of the native project",
feature: {
name: "js Middleware calls native methods through it"
},
uses-permission: "Open permissions"
}
}
}
- Add platform
plugman platform add --platform_name andorid/ios
//android will appear under src after adding
//The java file, js file and plugin.xml are initialized
- mytoast.java and mytoast.js
First let's look at mytoast.java
public class mytoast extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("showToast")) {
String message = args.getString(0);
this.showToast(message, callbackContext);
return true;
}
return false;
}
private void showToast(String message, CallbackContext callbackContext) {
if (message != null && message.length() > 0) {
Activity activity = this.cordova.getActivity();
android.widget.Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
callbackContext.success(message);
} else {
callbackContext.error("Expected one non-empty string argument.");
}
}
}
The method format of plugin is roughly the same. The execute method is required. The external call method passes the action field. According to the action, we can call the underlying related programs, and call the success method or error method through the CallbackContext. Here, we implement the showToast method. When the action is the "showToast" field, we perform the operation in if(action.equals("showToast") {}.
Accordingly, we also need to implement the corresponding method call in mytoast.js file
var exec = require('cordova/exec');
exports.showToast = function (msg, success, error) {
exec(success, error, 'mytoast', 'showToast', [msg]);
};
- Add package.json
//Directly init one in the toast plug-in folder
npm init
be accomplished!!!!!
install
- Create cordova project and install it
cordova create testplugin com.digichain.testplugin
cordova platform add android
cordova plugins add Plug-in address
- Add events to test under / www/js/index/js and run
cordova run android
Okkkkkkkkkkkkkk!!!!!!! Perfect!