How to call cordova android function from javascript?

cordova plugin example

TL;DR

You have to create plugin. There is no easier way how to do it. But you can create really simple one (much easier then that one from documentation) so continue reading!

Calling Android function from JavaScript

Let’s start with the easy part, the JavaScript part. To call your Android function all you have to do is this.

That’s nice but you need the Cordova plugin to do that so let’s create one!

How to create Cordova plugin

This is the hardest part and when you realize, you are creating plugin to call one function on the android side it’s just … So what are we doing? We are going to create Android plugin that will allow us to receive calls from Javascript .

cordova-example-plugin

├── package.json
├── plugin.xml
├── src
│   └── android
│       └── Example.java
└── www
    └── Example.js

Simple right? And you want it simpler then simple? Here it is ready to clone/download and rename.

DOWNLOAD EXAMPLE FILES

So what do we have here? Let’s look at Example.java. Do you remember the javascript part? Here we have Example class (3rd parameter) then our action (4th parameter) and our arguments are accessible in args parameter with args.getString(0).

Example.java

package.json

Example.js is empty. In package.json we have info about our plugin.

plugin.xml

in plugin.xml we have another info about our plugin. But notice here the line. In this file we tell Cordova about permissions we are asking for. (Internet permission is here just for the sakes of example)

Installation

What now? Now install it! Go to your cordova project and just copy paste the plugin there. Then run (in your project folder):

cordova plugin add ./cordova-example-plugin

You can have the plugin wherever you want, it doesn’t have to be in you project path, but remember that may come time when someone else will be pulling your project from repository and he will have your plugin as a dependency.

References

 

Buy me a coffeeOut of coffee 😱, please help!