Xamarin.Android Plugins
Plugins are used to communicate between C# code and the Cordova logic. With the plugin concept you could simply use any of your C# business logic inside of a Cordova app. If you want to access native features like the camera or file system, plugins are useful, too. The next steps will show you how to implement a simple Xamarin.Android Plugin.
Create a new class inside the Xamarin.Android project and inherit from CordovaPlugin.
Zühlke Engineering AG
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
public class TestPlugin : CordovaPlugin
{
protected override void PluginInitialize()
{
base.PluginInitialize();
}
public override bool Execute(string action, CordovaArgs args, CallbackContext p2)
{
if (action.Equals("echo"))
{
var message = args.Get(0).ToString();
Echo(message, p2);
return true;
}
return false;
}
private void Echo(String message, CallbackContext callbackContext)
{
if (message != null && message.Length > 0)
{
callbackContext.Success(message + " from Xamarin!");
}
}
}
|
The Execute method can be invoked from the Cordova code afterwards.
Create a new file called testplugin.js in the folder Assets/www. This file is the Cordova equivalent to the previously created C# class and manages the communication from the Cordova side.
Zühlke Engineering AG
|
1
2
3
4
5
6
7
8
|
var TestPlugin = function() {
};
TestPlugin.prototype.echo = function(str, callback) {
cordova.exec(callback, function(err) {
callback();
}, "TestPlugin", "echo", [str]);
};
|
The plugin can be used with the following sample code snippet:
Zühlke Engineering AG
|
var testPlugin = new TestPlugin();
testPlugin.echo("Good Evening", function(echoValue) {
alert(echoValue);
});
|
The plugin is dedicated to transport the string Good Evening to the Xamarin code. The Xamarin code attaches from Xamarin to the string and returns the result. Afterwards the Cordova app shows an alert window with the respective result.