Example usage for org.apache.cordova PluginResult setKeepCallback

List of usage examples for org.apache.cordova PluginResult setKeepCallback

Introduction

In this page you can find the example usage for org.apache.cordova PluginResult setKeepCallback.

Prototype

public void setKeepCallback(boolean b) 

Source Link

Usage

From source file:com.ibm.mqtt.android.cordova.plugin.MqttPlugin.java

License:Open Source License

@Override
/**/*from   w  w  w . j a va 2  s. c  o m*/
 * This method takes the data passed through from javascript via "cordova.exec" and
 * makes appropriate method calls to the service.
 * Most calls will respond by broadcasting intents which our callbacklistener handles
 * 
 * This is a large method, but falls naturally into sections based on the action being
 * processed, so it doesn't seem necessary to split it into multiple methods.
 * 
 * @param action the action to be performed (see MqttServiceConstants)
 * @param args the parameters specified by the javascript code
 * @param callbackId 
 *       the callbackId which can be used to invoke to the success/failure callbacks
 *       provide to the cordova.execute call
 */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    traceDebug(TAG, "execute(" + action + ",{" + args + "}," + callbackContext.getCallbackId() + ")",
            callbackContext);
    try {
        if (action.equals(MqttServiceConstants.START_SERVICE_ACTION)) {
            if (mqttService != null) {
                traceDebug(TAG, "execute - service already started", callbackContext);
                return true;
            }
            serviceIntent = new Intent(context, MqttService.class);
            serviceIntent.putExtra(MqttServiceConstants.CALLBACK_ACTIVITY_TOKEN,
                    callbackContext.getCallbackId());
            ComponentName serviceComponentName = context.startService(serviceIntent);

            if (serviceComponentName == null) {
                traceError(TAG, "execute() - could not start " + MqttService.class, callbackContext);
                return false;
            }

            if (context.bindService(serviceIntent, serviceConnection, 0)) {
                // we return Status.NO_RESULT and setKeepCallback(true)
                // so that the callbackListener can use this callbackId
                // when it receives a connected event
                PluginResult result = new PluginResult(Status.NO_RESULT);
                result.setKeepCallback(true);

                callbackContext.sendPluginResult(result);
                return true;
            }
            return false;
        }

        if (action.equals(MqttServiceConstants.SET_TRACE_CALLBACK)) {
            // This is a trifle inelegant
            traceCallbackId = callbackContext.getCallbackId();
            if (mqttService != null) {
                mqttService.setTraceCallbackId(callbackContext.getCallbackId());
            }
            PluginResult result = new PluginResult(Status.NO_RESULT);
            result.setKeepCallback(true);

            callbackContext.sendPluginResult(result);
            return true;
        }

        if (action.equals(MqttServiceConstants.SET_TRACE_ENABLED)) {
            traceEnabled = true;
            if (mqttService != null) {
                mqttService.setTraceEnabled(traceEnabled);
            }
            PluginResult result = new PluginResult(Status.OK);

            callbackContext.sendPluginResult(result);
            return true;
        }

        if (action.equals(MqttServiceConstants.SET_TRACE_DISABLED)) {
            traceEnabled = false;
            if (mqttService != null) {
                mqttService.setTraceEnabled(traceEnabled);
            }
            PluginResult result = new PluginResult(Status.OK);

            callbackContext.sendPluginResult(result);
            return true;
        }

        if (mqttService == null) {
            return false;
        }

        if (action.equals(MqttServiceConstants.STOP_SERVICE_ACTION)) {
            Intent serviceIntent = new Intent(context, MqttService.class);
            context.stopService(serviceIntent);
            mqttService = null;
            return true;
        }

        if (action.equals(MqttServiceConstants.GET_CLIENT_ACTION)) {
            // This is a simple operation and we do it synchronously
            String clientHandle;
            try {
                String host = args.getString(0);
                int port = args.getInt(1);
                String clientId = args.getString(2);
                clientHandle = mqttService.getClient(host, port, clientId);

                // Set up somewhere to hold callbacks for this client
                callbackMap.put(clientHandle, new HashMap<String, String>());
            } catch (JSONException e) {
                traceException(TAG, "execute()", e, callbackContext);
                return false;
            }
            // We return a clientHandle to the javascript client,
            // which it can use to identify the client on subsequent calls
            return true;
        }

        // All remaining actions have a clientHandle as their first arg
        String clientHandle = args.getString(0);

        if (action.equals(MqttServiceConstants.CONNECT_ACTION)) {
            int timeout = args.getInt(1);
            boolean cleanSession = args.getBoolean(2);
            String userName = args.optString(3);
            String passWord = args.optString(4);
            int keepAliveInterval = args.getInt(5);
            JSONObject jsMsg = args.optJSONObject(6);
            MessagingMessage willMessage = (jsMsg == null) ? null : messageFromJSON(jsMsg, callbackContext);
            boolean useSSL = args.getBoolean(7);
            Properties sslProperties = null;
            JSONObject jsSslProperties = args.getJSONObject(8);
            if (jsSslProperties.length() != 0) {
                sslProperties = new Properties();
                Iterator<?> sslPropertyIterator = jsSslProperties.keys();
                while (sslPropertyIterator.hasNext()) {
                    String propertyName = (String) sslPropertyIterator.next();
                    String propertyValue = jsSslProperties.getString(propertyName);
                    sslProperties.put("com.ibm.ssl." + propertyName, propertyValue);
                }
            }
            String invocationContext = args.optString(9);
            mqttService.connect(clientHandle, timeout, cleanSession, userName, passWord, keepAliveInterval,
                    willMessage, useSSL, sslProperties, invocationContext, callbackContext.getCallbackId());
            PluginResult result = new PluginResult(Status.NO_RESULT);
            result.setKeepCallback(true);

            callbackContext.sendPluginResult(result);
            return true;
        }

        if (action.equals(MqttServiceConstants.DISCONNECT_ACTION)) {
            String invocationContext = args.optString(1);
            mqttService.disconnect(clientHandle, invocationContext, callbackContext.getCallbackId());
            PluginResult result = new PluginResult(Status.NO_RESULT);
            result.setKeepCallback(true);

            callbackContext.sendPluginResult(result);
            return true;
        }

        if (action.equals(MqttServiceConstants.SEND_ACTION)) {
            JSONObject jsMsg = args.getJSONObject(1);
            MessagingMessage msg = messageFromJSON(jsMsg, callbackContext);
            String invocationContext = args.optString(2);
            mqttService.send(clientHandle, msg, invocationContext, callbackContext.getCallbackId());
            // we return Status.NO_RESULT and setKeepCallback(true)
            // so that the callbackListener can use this callbackId
            // at an appropriate time - what time that is depends on
            // the qos value specified.
            PluginResult result = new PluginResult(Status.NO_RESULT);
            result.setKeepCallback(true);

            callbackContext.sendPluginResult(result);
            return true;
        }

        if (action.equals(MqttServiceConstants.SUBSCRIBE_ACTION)) {
            String topicFilter = args.getString(1);
            int qos = args.getInt(2);
            String invocationContext = args.optString(3);
            mqttService.subscribe(clientHandle, topicFilter, qos, invocationContext,
                    callbackContext.getCallbackId());
            // we return Status.NO_RESULT and setKeepCallback(true)
            // so that the callbackListener can use this callbackId
            // when it receives an event from the subscribe operation
            PluginResult result = new PluginResult(Status.NO_RESULT);
            result.setKeepCallback(true);

            callbackContext.sendPluginResult(result);
            return true;
        }

        if (action.equals(MqttServiceConstants.UNSUBSCRIBE_ACTION)) {
            String topicFilter = args.getString(1);
            String invocationContext = args.optString(2);
            mqttService.unsubscribe(clientHandle, topicFilter, invocationContext,
                    callbackContext.getCallbackId());
            // we return Status.NO_RESULT and setKeepCallback(true)
            // so that the callbackListener can use this callbackId
            // when it receives an event from the unsubscribe operation
            PluginResult result = new PluginResult(Status.NO_RESULT);
            result.setKeepCallback(true);

            callbackContext.sendPluginResult(result);
            return true;
        }

        if (action.equals(MqttServiceConstants.ACKNOWLEDGE_RECEIPT_ACTION)) {
            // This is a synchronous operation
            String id = args.getString(1);
            return mqttService.acknowledgeMessageArrival(clientHandle, id);
        }

        // The remaining actions are used to register callbacks for
        // "unsolicited" events
        if (action.equals(MqttServiceConstants.SET_ON_CONNECTIONLOST_CALLBACK)) {
            return setCallback(clientHandle, MqttServiceConstants.ON_CONNECTION_LOST_ACTION, callbackContext);
        }
        if (action.equals(MqttServiceConstants.SET_ON_MESSAGE_DELIVERED_CALLBACK)) {
            return setCallback(clientHandle, MqttServiceConstants.MESSAGE_DELIVERED_ACTION, callbackContext);
        }
        if (action.equals(MqttServiceConstants.SET_ON_MESSAGE_ARRIVED_CALLBACK)) {
            boolean setCallbackResult = setCallback(clientHandle, MqttServiceConstants.MESSAGE_ARRIVED_ACTION,
                    callbackContext);
            return setCallbackResult;
        }

    } catch (JSONException e) {
        return false;
    } catch (IllegalArgumentException e) {
        return false;
    }

    return false;
}

From source file:com.ibm.mqtt.android.cordova.plugin.MqttPlugin.java

License:Open Source License

private boolean setCallback(String clientHandle, String action, CallbackContext callbackContext) {
    Map<String /* action */, String /* callbackId */> clientCallbacks = callbackMap.get(clientHandle);
    if (clientCallbacks == null) {
        return false;
    }//www . ja v a 2 s . c  om
    clientCallbacks.put(action, callbackContext.getCallbackId());
    PluginResult result = new PluginResult(Status.NO_RESULT);
    result.setKeepCallback(true); // keep it around

    callbackContext.sendPluginResult(result);
    return true;
}

From source file:com.ibm.mqtt.android.cordova.plugin.MqttPlugin.java

License:Open Source License

private void makeTraceCallback(Status status, String message, int errorCode, String severity,
        CallbackContext callbackContext) {
    if ((traceCallbackId != null) && (traceEnabled)) {
        JSONObject callbackResult = new JSONObject();
        try {//ww  w .  j av a  2s.  co m
            callbackResult.put("severity", severity);
            callbackResult.put("message", message);
            callbackResult.put("errorCode", errorCode);
        } catch (JSONException e) {
            Log.e(TAG, "failed to build callback result", e);
        }
        PluginResult pluginResult = new PluginResult(status, callbackResult);
        pluginResult.setKeepCallback(true);

        callbackContext.success(traceCallbackId);
    }
}

From source file:com.inbeacon.cordova.CordovaInbeaconManager.java

License:Apache License

/**
 * The final call you receive before your activity is destroyed.
 *///from  w w  w .j a  v a2 s  . c  o  m
public void onDestroy() {
    if (broadcastReceiver != null) {
        // unRegister our receiver that was registered on localbroadcastmanager
        // wrong: cordova.getActivity().unregisterReceiver(broadcastReceiver);
        LocalBroadcastManager.getInstance(cordova.getActivity().getApplicationContext())
                .unregisterReceiver(broadcastReceiver);

        broadcastReceiver = null;
    }

    // release events in JS side
    if (eventCallbackContext != null) {
        PluginResult result = new PluginResult(PluginResult.Status.OK);
        result.setKeepCallback(false);
        eventCallbackContext.sendPluginResult(result);
        eventCallbackContext = null;
    }

    super.onDestroy();
}

From source file:com.inbeacon.cordova.CordovaInbeaconManager.java

License:Apache License

/**
 * Send a new plugin result back to JavaScript, without closing callback
 *
 * @param data InBeacon event result containing message and extras
 */// w w  w . j  a va 2 s  . c o m
private void sendUpdate(JSONObject data) {
    if (this.eventCallbackContext != null) {
        PluginResult result = new PluginResult(PluginResult.Status.OK, data);
        result.setKeepCallback(true);
        this.eventCallbackContext.sendPluginResult(result);
    }
}

From source file:com.inbeacon.cordova.CordovaInbeaconManager.java

License:Apache License

/**
 * Send a new plugin result with no result. Use to keep callback channel open for events
 *///from   w  w w.  j a  va2s  .c  o  m
private void sendNoResult() {
    if (this.eventCallbackContext != null) {
        PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
        pluginResult.setKeepCallback(true);
        this.eventCallbackContext.sendPluginResult(pluginResult);
    }
}

From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowser.java

License:Apache License

/**
 * Executes the request and returns PluginResult.
 *
 * @param action          The action to execute.
 * @param args            The exec() arguments, wrapped with some Cordova helpers.
 * @param callbackContext The callback context used when calling back into JavaScript.
 * @return/*from  w  w  w. j a  v  a  2 s  .  com*/
 * @throws JSONException
 */
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext)
        throws JSONException {
    if (action.equals("open")) {
        this.callbackContext = callbackContext;
        final String url = args.getString(0);
        String t = args.optString(1);
        if (t == null || t.equals("") || t.equals(NULL)) {
            t = SELF;
        }
        final String target = t;
        final Options features = parseFeature(args.optString(2));
        customSchema = features.customSchema;

        this.cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String result = "";
                // SELF
                if (SELF.equals(target)) {
                    /* This code exists for compatibility between 3.x and 4.x versions of Cordova.
                     * Previously the Config class had a static method, isUrlWhitelisted(). That
                     * responsibility has been moved to the plugins, with an aggregating method in
                     * PluginManager.
                     */
                    Boolean shouldAllowNavigation = null;
                    if (url.startsWith("javascript:")) {
                        shouldAllowNavigation = true;
                    }
                    if (shouldAllowNavigation == null) {
                        shouldAllowNavigation = new Whitelist().isUrlWhiteListed(url);
                    }
                    if (shouldAllowNavigation == null) {
                        try {
                            Method gpm = webView.getClass().getMethod("getPluginManager");
                            PluginManager pm = (PluginManager) gpm.invoke(webView);
                            Method san = pm.getClass().getMethod("shouldAllowNavigation", String.class);
                            shouldAllowNavigation = (Boolean) san.invoke(pm, url);
                        } catch (NoSuchMethodException e) {
                        } catch (IllegalAccessException e) {
                        } catch (InvocationTargetException e) {
                        }
                    }
                    // load in webview
                    if (Boolean.TRUE.equals(shouldAllowNavigation)) {
                        webView.loadUrl(url);
                    }
                    //Load the dialer
                    else if (url.startsWith(WebView.SCHEME_TEL)) {
                        try {
                            Intent intent = new Intent(Intent.ACTION_DIAL);
                            intent.setData(Uri.parse(url));
                            cordova.getActivity().startActivity(intent);
                        } catch (android.content.ActivityNotFoundException e) {
                            emitError(ERR_CRITICAL, String.format("Error dialing %s: %s", url, e.toString()));
                        }
                    }
                    // load in ThemeableBrowser
                    else {
                        result = showWebPage(url, features);
                    }
                }
                // SYSTEM
                else if (SYSTEM.equals(target)) {
                    result = openExternal(url);
                }
                // BLANK - or anything else
                else {
                    result = showWebPage(url, features);
                }

                PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result);
                pluginResult.setKeepCallback(true);
                callbackContext.sendPluginResult(pluginResult);
            }
        });
    } else if (action.equals("close")) {
        closeDialog();
    } else if (action.equals("injectScriptCode")) {
        String jsWrapper = null;
        if (args.getBoolean(1)) {
            jsWrapper = String.format("prompt(JSON.stringify([eval(%%s)]), 'gap-iab://%s')",
                    callbackContext.getCallbackId());
        }
        injectDeferredObject(args.getString(0), jsWrapper);
    } else if (action.equals("injectScriptFile")) {
        String jsWrapper;
        if (args.getBoolean(1)) {
            jsWrapper = String.format(
                    "(function(d) { var c = d.createElement('script'); c.src = %%s; c.onload = function() { prompt('', 'gap-iab://%s'); }; d.body.appendChild(c); })(document)",
                    callbackContext.getCallbackId());
        } else {
            jsWrapper = "(function(d) { var c = d.createElement('script'); c.src = %s; d.body.appendChild(c); })(document)";
        }
        injectDeferredObject(args.getString(0), jsWrapper);
    } else if (action.equals("injectStyleCode")) {
        String jsWrapper;
        if (args.getBoolean(1)) {
            jsWrapper = String.format(
                    "(function(d) { var c = d.createElement('style'); c.innerHTML = %%s; d.body.appendChild(c); prompt('', 'gap-iab://%s');})(document)",
                    callbackContext.getCallbackId());
        } else {
            jsWrapper = "(function(d) { var c = d.createElement('style'); c.innerHTML = %s; d.body.appendChild(c); })(document)";
        }
        injectDeferredObject(args.getString(0), jsWrapper);
    } else if (action.equals("injectStyleFile")) {
        String jsWrapper;
        if (args.getBoolean(1)) {
            jsWrapper = String.format(
                    "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%s; d.head.appendChild(c); prompt('', 'gap-iab://%s');})(document)",
                    callbackContext.getCallbackId());
        } else {
            jsWrapper = "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %s; d.head.appendChild(c); })(document)";
        }
        injectDeferredObject(args.getString(0), jsWrapper);
    } else if (action.equals("show")) {
        this.cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dialog.show();
            }
        });
        PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
        pluginResult.setKeepCallback(true);
        this.callbackContext.sendPluginResult(pluginResult);
    } else if (action.equals("reload")) {
        if (inAppWebView != null) {
            this.cordova.getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    inAppWebView.reload();
                }
            });
        }
    } else {
        return false;
    }
    return true;
}

From source file:com.intel.cordovacontext.CordovaContext.java

License:Open Source License

private JSONObject processItemState(Item state, boolean executeCallback) {
    // Covert state into a JSONObject
    // I can't find a good way to do it with the Android JSONObject,
    // So I used GSON and then parse it into JSONObject.
    JSONObject data = new JSONObject();
    String json = new Gson().toJson(state);
    try {/*from   ww w . ja  v  a  2  s.c om*/
        data = new JSONObject(json);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (executeCallback) {
        CallbackContext callbackContext = null;

        if (CallbackCache.containsKey(state.getContextType()))
            callbackContext = CallbackCache.get(state.getContextType());

        if (callbackContext != null) {
            PluginResult result = new PluginResult(PluginResult.Status.OK, data);
            result.setKeepCallback(true);
            callbackContext.sendPluginResult(result);
        }
    }

    return data;
}

From source file:com.ironsmile.cordova.mediaevents.MediaEventListener.java

License:Apache License

/**
 * Executes the request./*w w w .  j a  va 2 s.  c om*/
 *
 * @param action            The action to execute.
 * @param args              JSONArry of arguments for the plugin.
 * @param callbackContext   The callback context used when calling back into js
 * @return                  True if the action was valid, false if not.
 */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    if (action.equals("start")) {
        if (this.eventCallbackContext != null) {
            callbackContext.error("Media event listener already running.");
            return true;
        }
        this.eventCallbackContext = callbackContext;

        // We need to listen to audio events
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);

        if (this.receiver == null) {
            this.receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    sendMediaEvent(intent);
                }
            };
            cordova.getActivity().registerReceiver(this.receiver, intentFilter);
        }

        if (this.focusListener == null) {
            Context ctx = cordova.getActivity().getBaseContext();
            this.focusListener = this.new FocusListener(ctx);
        }

        // Don't return any result now, since status results will be sent when 
        // events come in from broadcast receiver
        PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        return true;
    }

    else if (action.equals("stop")) {
        removeMediaEventListener();
        // release status callback in JS side
        this.sendUpdate(new JSONObject(), false);
        this.eventCallbackContext = null;
        callbackContext.success();
        return true;
    }

    return false;
}

From source file:com.ironsmile.cordova.mediaevents.MediaEventListener.java

License:Apache License

/**
 * Create a new plugin result and send it back to JavaScript
 *
 * @param connection the network info to set as navigator.connection
 *///from  w ww  .j  ava  2  s  .  c om
private void sendUpdate(JSONObject info, boolean keepCallback) {
    if (this.eventCallbackContext != null) {
        PluginResult result = new PluginResult(PluginResult.Status.OK, info);
        result.setKeepCallback(keepCallback);
        this.eventCallbackContext.sendPluginResult(result);
    }
}