Reputation: 8337
I wrote a Cordova plugin for Android to build a phonegap app with an HTML5 GUI.
I now want to have a native interface too and was wondering what is the neatest option to reuse my plugin for the native UI. Basically I would like to have two apps, one with a phonegap (HTML5) interface and one with a native Android interface, both of them using the Cordova plugin.
The plugin extends the CordovaPlugin
class, so for this reason I don't know how to use it without calling the following method from the javascript in the WebView
, as described here http://docs.phonegap.com/en/2.3.0/guide_plugin-development_android_index.md.html
exec(<successFunction>, <failFunction>, <service>, <action>, [<args>]);
I just want to call the native side of the plugin without going through a WebView
:
@Override
public boolean execute(String action, JSONArray args,
CallbackContext callbackContext) throws JSONException { ... }
Provided that I could just adapt the code from the plugin fairly easily, I would like to find a method by which the plugin remains exactly the same for better decoupling of frontend/backend (I could change the code in one app without the need to replicate it in the other app).
Is this possible at all? I understand this is not the point of having a Cordova plugin, but I would like to find a way around it.
Thanks.
Upvotes: 0
Views: 3979
Reputation: 3169
In my opinion you need to apply Facade pattern
:
http://en.wikipedia.org/wiki/Facade_pattern
Simply extract your business logic from Cordova plugin to dedicated class called MyFacade
and hide all your business logic behind.
The other way is to do something like this:
MyCordovaPlugin myPlugin = new MyCordovaPlugin();
myPlugin.execute("foo", new JSONArray(), new MyCallbackContext() {
@override
public void handlePluginResult(PluginResult pluginResult) {
//your code for handling plugin result for Android UI
}
}
Where MyCallbackContext
implementation is:
public abstract class MyCallbackContext extends CallbackContext {
public MyCallbackContext() {
super(null, null);
}
public void sendPluginResult(PluginResult pluginResult) {
synchronized (this) {
if (finished) {
Log.w(LOG_TAG, "Attempted to send a second callback for ID: " + callbackId + "\nResult was: " + pluginResult.getMessage());
return;
} else {
finished = !pluginResult.getKeepCallback();
}
}
handlePluginResult(pluginResult);
}
public abstract void handlePluginResult(PluginResult pluginResult);
}
This second way works only with current version of Cordova and is based on this source codes:
Upvotes: 1