Objective
This article is suitable for Android+web's complex talent, because Cordova itself is a hybrid development, so on the basis of Android development, but also understand the web-related technology (HTML+CSS+JS), but there are exceptions, such as I, just responsible for Android, Web aspects are developed by other Web group personnel. Although, the web a little bit, but I am mainly engaged in the development of Android.
Writing custom plug-in classes
The content of this section is to customize a dialog plug-in for the web call that displays the system pop-up window.
Create a new package name, I use Org.apache.cordova.dialog here, then create Class Customdialog.java, inherit from Cordovaplugin (all custom plugins, inherit Cordovaplugin), and finally rewrite the Execute method.
Execute has three overloaded methods:
publicbooleanexecute(String action, JSONArray args, CallbackContext callbackContext)
publicbooleanexecute(String action, CordovaArgs args, CallbackContext callbackContext)
publicboolean execute(StringString rawArgs, CallbackContext callbackContext)
These three methods, if you look at the Cordovaplugin source, you will find, in fact, the last call to the second method, but Cordovaargs just a package for jsonarray, easy to manipulate JSON data, so to rewrite which, according to personal preferences.
Here, I am rewriting the second method, now to illustrate the following method parameters:
String Action: A class can provide multiple functions, and the action is to call which function is called.
Cordovaargs args:web in JSON data format to Android Native,cordovaargs is an encapsulation of jsonarray.
Callbackcontext Callbackcontext: This is a callback to the Web, there are success and error two callback methods.
The specific implementation is as follows:
Public class customdialog extends cordovaplugin{ @Override Public Boolean Execute(String action, Cordovaargs args,FinalCallbackcontext Callbackcontext)throwsjsonexception {if("Show". Equals (Action) {Alertdialog.builder Builder =NewAlertdialog.builder (Cordova.getactivity ()); Builder.settitle ("Hint"); Builder.setmessage (Args.getstring (0)); Builder.setpositivebutton ("OK",NewDialoginterface.onclicklistener () {@Override Public void OnClick(Dialoginterface Dialog,intwhich) {Dialog.dismiss (); Callbackcontext.success ("Clicked OK"); } }); Builder.setnegativebutton ("Cancel",NewDialoginterface.onclicklistener () {@Override Public void OnClick(Dialoginterface Dialog,intwhich) {Dialog.dismiss (); Callbackcontext.error ("Clicked Cancel"); } }); Builder.create (). Show ();return true; }return Super. Execute (Action, args, Callbackcontext); }}
If the web uses the Customdialog plug-in, and calls the Show method (action). At this point, a system window pops up, displaying the message content sent over the web, clicking OK, calling back to the web, telling it that the call was successful, and canceling the failure. Finally, remember to return True (indicates successful invocation).
Configuring CONFIG.
Open the Res/xml/config.xml file with the original content as follows:
<?xml version= ' 1.0 ' encoding= ' utf-8 '?><widget id="Com.example.helloworld" version="0.0.1 " xmlns="Http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/ 1.0 "> <preference name="LogLevel" value="DEBUG" /> <feature name="Whitelist"> <param name= "android-package" value=" Org.apache.cordova.whitelist.WhitelistPlugin " /> <param name="onload" value="true" /> </feature> <allow-intent href="market:*" /> <name>HelloWorld</name> <description>A Sample Apache Cordova application that responds to the Deviceready event.</Description> <author Email="[email protected]" href="Http://cordova.io" >Apache Cordova Team</author> <content src="index.html" /> <access origin="*" /> <allow-intent href="http://*/*" /> <allow-intent href="https://*/*" /> <allow-intent href="tel:*" /> <allow-intent href="sms:*" /> <allow-intent href="mailto:*" /> <allow-intent href="geo:*" /></Widgets>
Whitelist is a plugin that comes with the base project, and we also add a feature under the widget node.
<?xml version= ' 1.0 ' encoding= ' utf-8 '?><widget id="Com.example.helloworld" version="0.0.1" xmlns ="Http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0" > <preference name="LogLevel" value="DEBUG" /> <feature name="Whitelist"> <param name= "android-package" value=" Org.apache.cordova.whitelist.WhitelistPlugin " /> <param name="onload" value="true" /> </feature> <!--pop-up windows-- <feature name="Customdialog"> <param name= "android-package" value=" Org.apache.cordova.dialog.CustomDialog " /> </feature> <allow-intent href="market:*" /> <name>HelloWorld</name> <description>A Sample Apache Cordova application that responds to the Deviceready event.</Description> <author Email="[email protected]" href="Http://cordova.io" >Apache Cordova Team</author> <content src="index.html" /> <access origin="*" /> <allow-intent href="http://*/*" /> <allow-intent href="https://*/*" /> <allow-intent href="tel:*" /> <allow-intent href="sms:*" /> <allow-intent href="mailto:*" /> <allow-intent href="geo:*" /></Widgets>
Feature name can be arbitrarily taken, param value is filled with the location of the specific class.
Web configuration and call 1, configure
Open the Asserts/www/cordova_plugins.js file and register the plugin.
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-dialog/dialog.js",//js file path "id":"Cordova-plugin-dialog. Customdialog ",ID of//js cordova.define "Clobbers": ["Alertdialog"method Name when//js is called]}];module.exports.metadata =//TOP of METADATA{"Cordova-plugin-whitelist":"1.2.1"};//BOTTOM of METADATA});
Then create the Dialog.js file under Assets/www
The contents are as follows:
Cordova.define ("Cordova-plugin-dialog. Customdialog ", function(require, exports, module) {var exec =require("Cordova/exec");Module. Exports = {show: function(content) {EXEC ( function(message) {//Successful callback functionconsole.log(message) ; }, function(message) {//Failure callback functionconsole.log(message) ; },"Customdialog",//feature name"Show",//action [content]//to pass the parameters, JSON format]; } }});
The first parameter of Cordova.define is the ID defined in Cordova_plugins.js, the most important is the Exec method, parameter description:
Parameter 1: Successful callback function
Parameter 2: Failed callback function
Parameter 3:feature name, consistent with the registration in CONFIG.
Parameter 4: Action when invoking the Java class
Parameter 5: Parameters to pass, JSON format
2. Call
After configuring the above, only the appropriate place to call it.
Open Assets/www/js/index.js
Locate the Ondeviceready method, and then call
alertDialog.show(‘Hello World!!!!‘);
Here directly call Alertdialog, is defined under the Cordova_plugins.js clobbers name, show is the function of JS declaration
Index.js#ondeviceready
function() { app.receivedEvent(‘deviceready‘); //调用自定义插件 alertDialog.show(‘Hello World!!!!‘); }
Run directly in Android Studio, as follows:
This dialog box is the Alertdialog of the Android system. When we click OK, we will callback JS success function, print out the log.
do not execute the Cordova build command!!!
It is important to note that if you read the last chapter carefully, you will have a question that compiling the project is not
cordova build
Command? Very good, online a lot of said, in the project, the code has been written, but the execution of the command, not only did not take effect, but the previous write plug-in code is gone. In fact, if you know the whole project compile process, then the problem is solved.
Here's a simple, look at the directory structure
Plugins is the folder where the plugin is stored, and WWW is the file that holds the H5 project, which is the asserts/www under the Android project, when the Cordova build is executed, It compiles the project according to CONFIG. Plugins and www files are then applied to each platform under the Platforms folder, which is "once compiled, multi-platform run".
However, from the beginning to the end, we wrote the code is under the Android platform, and the above mentioned two folders we have not moved, that is, all configurations are not moved, is the initial state, so the implementation of the build will not be effective.
Summarize
With the above example, a simple custom plugin has been implemented, but it is only implemented on the Android platform. So, how do we apply it to other platforms? Or, after we implement a plugin, how do we offer it to someone else's project? In the next section, we will talk about how the plug-in installation package is built to solve these problems.
Source
Android Cordova Plugin Development to write custom plugins