Write an Android plugin for PhoneGap

Source: Internet
Author: User

Write an Android plugin for PhoneGap, what do I do?

In fact this sentence should be said in turn, for Android to write a PhoneGap plugin, how to do?

Here is an example of the simplest Hello world!, a description:

1, the first step, the first to establish a support PhoneGap (Cordova) Android Project

Because this plug-in is essentially an Android plugin for PhoneGap, so we need to support both, so we're going to build an Android project that supports PhoneGap (Cordova), and the plugin is written in this project.

Literacy: PhoneGap has now been sold to the Apache Foundation and is now renamed Cordova. The name was used because the company that created PhoneGap was in a street called Cordova, presumably to commemorate it. Now to download the latest Cordova, should go to Cordova official website, and PhoneGap official website stayed in 2.9.1.

We use the Cordova CLI to create the project. This will be more convenient. Otherwise you have to create an Android project, and then manually copy the Cordova to the project folder, but also to modify the code, very troublesome.


1) Create a Cordova project first

In the command line mode:

Cordova Create Hello Com.example.test HelloWorld

This creates a folder called Hello in the current path, which is a file of Cordova


2) Set Cordova support Android platform

In the command line mode:

CD Hellocordova Platform add Android

So in the Hello\platforms folder, a more Android subdirectory, this is our support for the Phoegap Android project, plug-ins can be written in this project.

2. Write plugins

1) Hello.java

Open the project with Eclipse

New package and class under SRC

Hello.java:

Package Com.example.test.plugin;import Org.apache.cordova.callbackcontext;import Org.apache.cordova.CordovaPlugin ; Import Org.json.jsonarray;import Org.json.jsonexception;public class Hello extends cordovaplugin{@Override  Public Boolean execute (String action, Jsonarray args, Callbackcontext callbackcontext) throws Jsonexception {try{if (a Ction.equals ("SayHello")) {callbackcontext.success ("Hello world! hello, Cordoba! "); return true; }} catch (Exception e) {callbackcontext.error ("Oh shit!"); return false;}    Return Super.execute (action, args, Callbackcontext); }}

2) Config

Modify Res/xml/config.xml

Add in node <widget>:

<feature name= "Hello" ><param name= "Android-package" value= "Com.example.test.plugin.Hello"/></ Feature>  

3. Call Plugin

The call is JavaScript preserving.

1) Add Js/plugin.js
var helloplugin = {    say:function (successcallback, errorcallback) {        cordova.exec (            successcallback,// Success callback function            Errorcallback,//Error callback function            ' Hello ',//mapped to our native Java class CA  Lled "Calendarplugin"            ' SayHello ',//With the action name            []                 //And this array of the custom arguments to create Our entry        );}     }


2) Modify Js/index.js
Modify part mainly at the end part
var app = {//Application Constructor initialize:function () {this.bindevents (); },//Bind Event Listeners////bind any events is required on startup.    Common Events is://' load ', ' deviceready ', ' Offline ', and ' online '.    Bindevents:function () {document.addeventlistener (' Deviceready ', This.ondeviceready, false); },//Deviceready event Handler////The scope of ' this ' is the event.    In order to call the ' receivedevent '/function, we must explicitly call ' App.receivedevent (...); '    Ondeviceready:function () {app.receivedevent (' deviceready '); },//Update DOM on a Received Event receivedevent:function (id) {var parentelement = document.getelementbyi        D (ID);        var listeningelement = Parentelement.queryselector ('. listening ');        var receivedelement = Parentelement.queryselector ('. Received ');        Listeningelement.setattribute (' style ', ' display:none; '); Receivedelement.setattribute ('Style ', ' display:block; ');    Console.log (' Received Event: ' + id '); App.sayhello (); },sayhello:function () {var success = function (message) {alert (message);};    var error = function (message) {alert ("oopsie!" + message);}; Helloplugin.say (success, error);};


3) Modify Homepage index.html
        <script type= "Text/javascript" src= "cordova.js" ></script>        <script type= "Text/javascript" src= " Js/index.js "></script>        <script type=" Text/javascript "src=" Js/plugin.js "></script>        <script type= "Text/javascript" >            app.initialize ();        </script>

At this point, we have completed the process of writing and invoking the Android plugin for PhoneGap. As a principle, plug-ins should be independent of the specific project, can be used for multiple engineering calls, but this example is the plug-in directly written in the project. Independent way, I still don't know how to write.


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.