So, everyone knows that we create a class that extends CordovaPlugin and redefine execute() , and then create a bridge between JS and native Java (for Android). Next, we use PluginResult to return the result to JS.
So, all this happens when there is a request running from JS to the Java plugin. My question is: how to send the result back to JS (and therefore in HTML) asynchronously?
I don't know if the word will be asynchronous right here. The thing is, I want to send something back to JS from blue (let's say when wifi becomes on / off).
I have already researched this, but have not received anything that suits my case.
What I tried is
- Created
BroadcastReceiver , listening to WiFi events using the WifiManager class. - Register the receiver.
- And finally, when you click
Toast when WiFi on / off, and sends the result using CallbackContext
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, "Wifi Connected")) and to disconnect with another message.
MyPlugin.java
import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.json.JSONArray; ... public class MyPlugin extends CordovaPlugin { private WifiReceiver wifiBroadcastReceiver = null; private CallbackContext callbackContext = null; ... public MyPlugin() { wifiBroadcastReceiver = new WifiReceiver(); ... } ... public boolean execute(String action, final JSONArray args, final CallbackContext callbackId) throws JSONException { IntentFilter wifiFilter = new IntentFilter(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION); cordova.getActivity().registerReceiver(wifiBroadcastReceiver, wifiFilter); this.callbackContext = callbackId; ... } public class WifiReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) { if (intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false)) { Toast.makeText(cordova.getActivity(), "Wifi Connected", Toast.LENGTH_SHORT).show(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, "Wifi Connected")); } else { Toast.makeText(cordova.getActivity(), "Wifi Disconnected", Toast.LENGTH_SHORT).show(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Wifi Disconnected")); } } } }
Toast ports, but PluginResult not sent to JS.
PS: Listening to WiFi events is not my real problem, I want to replicate the Android Bluetooth Chat application in Phonegap. Therefore, it must be asynchronous in nature.
java android cordova phonegap-plugins
Anas Azeem 04 Oct '13 at 9:37
source share