Usually, the cordova plugin is used to invoke native api from javascript. However, it can also be used by javascript to listen for native side notification. This feature is already used in several cordova build in plugins, such as device motion plugin at https://github.com/apache/cordova-plugin-device-motion.
The basic idea is when calling the cordova plugin's callback method, it also an option to keep the callback alive, so after the cordova plugin API is initially called from javascritp to native side, the native code can keep the callback method in its data member. Whenever the native code needs to send a notification to javascript, it can just call this saved callback method with the notification data, also specify the callback method should be kept alive on javascirpt side in order to get following notification, otherwise, the javascript will delete the callback after it receives the first callback method from native side.
A sample callback made from Android native code are as below
The basic idea is when calling the cordova plugin's callback method, it also an option to keep the callback alive, so after the cordova plugin API is initially called from javascritp to native side, the native code can keep the callback method in its data member. Whenever the native code needs to send a notification to javascript, it can just call this saved callback method with the notification data, also specify the callback method should be kept alive on javascirpt side in order to get following notification, otherwise, the javascript will delete the callback after it receives the first callback method from native side.
A sample callback made from Android native code are as below
PluginResult result = new PluginResult(PluginResult.Status.OK, "This is notification data");
result.setKeepCallback(true);
_callbackContext.sendPluginResult(result);
No comments:
Post a Comment