cordova-support-android-plugin
The plugin introduces new base class for Android Cordova plugins called ReflectiveCordovaPlugin
that extends CordovaPlugin
and allows to reduce boilerplate code.
Index
Default implementation of execute
This is an example of typical cordova plugin implementation:
public class MyPlugin extends CordovaPlugin {
private static final String METHOD_1 = "method1";
private static final String METHOD_2 = "method2";
@Override
public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {
if (METHOD_1.equals(action)) {
method1(args, callbackContext);
} else if (METHOD_2.equals(action)) {
method2(callbackContext);
} else {
return false;
}
return true;
}
protected void method1(CordovaArgs args, CallbackContext callbackContext) {
}
protected void method2(CallbackContext callbackContext) {
}
}
Below is equal of code using ReflectiveCordovaPlugin
:
import by.chemerisuk.cordova.support.ReflectiveCordovaPlugin;
public class MyPlugin extends ReflectiveCordovaPlugin {
@CordovaMethod
protected void method1(CordovaArgs args, CallbackContext callbackContext) {
}
@CordovaMethod
protected void method2(CallbackContext callbackContext) {
}
}
Asynchronous actions
Cordova best practise is to invoke time-consuming logic in a separate thread:
public class MyPlugin extends CordovaPlugin {
private static final String METHOD_1 = "method1";
@Override
public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {
if (METHOD_1.equals(action)) {
method1(callbackContext);
} else {
return false;
}
return true;
}
protected void method1(CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable {
@Override
public void run() {
}
});
}
}
@CordovaMethod
annotation allows to specify execution thread as enumaration paratemer:
import by.chemerisuk.cordova.support.ReflectiveCordovaPlugin;
import static by.chemerisuk.cordova.support.ExecutionThread.WORKER;
public class MyPlugin extends ReflectiveCordovaPlugin {
@CordovaMethod(WORKER)
protected void method1(CallbackContext callbackContext) {
}
}
ProGuard notes
Only needed for version 1.
If you obfuscate app with ProGuard then proguard-rules.pro
usually contains rules:
-keep class org.apache.cordova.* { *; }
-keep class org.apache.cordova.engine.* { *; }
-keep public class * extends org.apache.cordova.CordovaPlugin
ReflectiveCordovaPlugin
uses method names to match an appropriate action. Therefore you should keep names for methods with @CordovaMethod
annotation:
-keepclassmembers class ** {
@by.chemerisuk.cordova.support.CordovaMethod *;
}
keep public enum by.chemerisuk.cordova.support.ReflectiveCordovaPlugin$** {
**[] $VALUES;
public *;
}