The Android Cordova plugin developed to write its own definition plugin

Source: Internet
Author: User
Tags call back

Objective

This article is suitable for Android+web's compound talented person, because the Cordova itself is the mixed development, therefore on the Android Development Foundation, also must understand the Web related technology (HTML+CSS+JS). But there are exceptions, for example, me. Just be responsible for the Android side. The web is being developed by other Web group personnel. Although. The web is a little bit more. But I am mainly engaged in the development of Android.

Writing your own definition plug-in class

The content of this section is. Define a dialog plugin yourself. For the web call to display the system popup.
Create a new package name, I use Org.apache.cordova.dialog here. Then create a class Customdialog.java. Inherit from Cordovaplugin (all self-defining plug-ins, 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. Let's say you read the Cordovaplugin source code. Will find that the second method is actually called in the end, but Cordovaargs is only a package for Jsonarray. It's easy to manipulate JSON data, so which one to rewrite. by personal preference.

Over here. I am rewriting the second method, now to illustrate the following method:
String Action: A class can provide multiple functions, the action is named to invoke which function.
Cordovaargs Args:web is passed to Android native in JSON data format. Cordovaargs is a package for the Jsonarray.
Callbackcontext Callbackcontext: This is a callback to the Web, there are success and error two callback methods.

Detailed implementations such as the following:

 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); }}

Suppose the web uses the Customdialog plug-in. And call the Show method (action). At this point, a system form will pop up. It will show the content of the message sent by the Web, click OK, call back the Web, tell it to be successful, and Cancel to fail. Finally, remember to return True (indicates successful invocation).

Configuring CONFIG.

Open the Res/xml/config.xml file with the original content such as the following:

<?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 the same, 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 detailed class.

Web configuration and call 1, configure

Open asserts/www/cordova_plugins.js file, register 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]//the number of parameters to pass.            JSON format); }        }});

The first parameter of Cordova.define is the ID defined in the Cordova_plugins.js, the most basic is the Exec method, the number of parameters:
Number 1: Successful callback function
Parameter 2: Failure callback function
Reference 3:feature name, consistent with the Register in config.
Parameter 4: Action when invoking the Java class
Parameter 5: The number of parameters to pass, in JSON format

2. Call

Complete the above configuration. The only thing left is to call it in the right place.
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, such as the following:

This dialog box is the Alertdialog of the Android system.

When we click OK. It will callback JS success function, print out the log.

Do not run the Cordova build command.


It is important to note that. Assuming you've looked at it carefully in the last chapter, you'll have a question that compiling a project is not

cordova build

Command? Very good, online very much said. In the project. The code is already written. However, a run of the command, not only did not take effect, but the previous write plug-in code is gone. In fact, suppose you know the entire project compilation process. Then the problem is solved.

Here's a brief. Look at the directory structure

Plugins is the directory where plugins are stored. And www is the storage H5 project. This is the file under Asserts/www under the Android project, and when you run Cordova build, It compiles the project according to CONFIG. Plugins and www files are then applied to each platform under the platforms directory, which is "once compiled, multi-platform run".

But. From the beginning to the end, all the code we wrote was on the Android platform. And none of the two directories mentioned above have ever been moved. In other words, all configurations are not moved. Is the initial state, so there is no effect after running the build.

Summarize

Through the above example, has implemented a simple self-defined plug-in, 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 generated. is to solve these problems.

Source

The Android Cordova plugin developed to write its own definition plugin

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.