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.jamiealtizer.cordova.inappbrowser.InAppBrowser.java

License:Apache License

/**
 * Executes the request and returns PluginResult.
 *
 * @param action        The action to execute.
 * @param args          JSONArry of arguments for the plugin.
 * @param callbackId    The callback id used when calling back into JavaScript.
 * @return              A PluginResult object with a status and message.
 *//*from w  w  w.  j  a  v  a2s.c  o m*/
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 HashMap<String, Boolean> features = parseFeature(args.optString(2));

        Log.d(LOG_TAG, "target = " + target);

        this.cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String result = "";
                // SELF
                if (SELF.equals(target)) {
                    Log.d(LOG_TAG, "in self");
                    /* 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) {
                        try {
                            Method iuw = Config.class.getMethod("isUrlWhiteListed", String.class);
                            shouldAllowNavigation = (Boolean) iuw.invoke(null, url);
                        } catch (NoSuchMethodException e) {
                        } catch (IllegalAccessException e) {
                        } catch (InvocationTargetException e) {
                        }
                    }
                    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)) {
                        Log.d(LOG_TAG, "loading in webview");
                        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) {
                            LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
                        }
                    }
                    // load in InAppBrowser
                    else {
                        result = showWebPage(url, features);
                    }
                }
                // SYSTEM
                else if (SYSTEM.equals(target)) {
                    Log.d(LOG_TAG, "in system");
                    result = openExternal(url);
                }
                // BLANK - or anything else
                else {
                    Log.d(LOG_TAG, "in blank");
                    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 {
        return false;
    }
    return true;
}

From source file:com.jcesarmobile.plusonebutton.PlusOneButtonPlugin.java

License:Apache License

/**
 * Executes the request and returns PluginResult.
 *
 * @param action            The action to execute.
 * @param args              JSONArry of arguments for the plugin.
 * @param callbackContext   The callback context from which we were invoked.
 *///  w  ww  .ja  va  2 s. c om
@SuppressLint("NewApi")
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext)
        throws JSONException {
    if (action.equals("show")) {
        if (args.optJSONObject(0) != null) {
            JSONObject obj = args.getJSONObject(0);
            URL = obj.optString("url", null);
            if (URL == null) {
                callbackContext.error("you have to provide an url");
            }
            x = obj.optJSONObject("position").optLong("x", 0);
            y = obj.optJSONObject("position").optLong("y", 0);
            size = obj.optInt("size", 3);
            annotation = obj.optInt("annotation", 1);
        } else if (args.optString(0) != null) {
            URL = args.optString(0);
        } else {
            callbackContext.error("you have to provide an url");
        }
        if (mPlusOneButton == null) {
            mPlusOneButton = new PlusOneButton(cordova.getActivity());
        }

        cordova.getActivity().runOnUiThread(new Runnable() {
            public void run() {
                mPlusOneButton.initialize(URL, null);
                mPlusOneButton.setVisibility(View.VISIBLE);
                if (!created) {
                    cordova.getActivity().addContentView(mPlusOneButton,
                            new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                                    RelativeLayout.LayoutParams.WRAP_CONTENT));
                    created = true;
                }
                mPlusOneButton.setX(x);
                mPlusOneButton.setY(y);
                mPlusOneButton.setSize(size);
                mPlusOneButton.setAnnotation(annotation);
            }
        });

    } else if (action.equals("hide")) {
        if (mPlusOneButton != null) {
            cordova.getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    mPlusOneButton.setVisibility(View.GONE);
                }
            });
        }
    } else if (action.equals("onClick")) {
        if (mPlusOneButton != null) {
            callback = callbackContext;
            mPlusOneButton.setOnPlusOneClickListener(new PlusOneButton.OnPlusOneClickListener() {
                @Override
                public void onPlusOneClick(Intent intent) {
                    System.out.println("1 Click!");

                    PluginResult result = new PluginResult(PluginResult.Status.OK);
                    result.setKeepCallback(true);
                    callback.sendPluginResult(result);

                    cordova.startActivityForResult(PObtn, intent, 0);
                }
            });
        }
    } else {
        return false;
    }
    return true;
}

From source file:com.jcesarmobile.plusonebutton.PlusOneButtonPlugin.java

License:Apache License

@Override
public void onResume(boolean multitasking) {
    super.onResume(multitasking);
    if (mPlusOneButton != null) {
        mPlusOneButton.initialize(URL, null);
        mPlusOneButton.setOnPlusOneClickListener(new PlusOneButton.OnPlusOneClickListener() {
            @Override// w ww  .  j  a va 2 s  . c  o  m
            public void onPlusOneClick(Intent intent) {
                System.out.println("2 Click!");

                PluginResult result = new PluginResult(PluginResult.Status.OK);
                result.setKeepCallback(true);
                callback.sendPluginResult(result);

                cordova.startActivityForResult(PObtn, intent, 0);
            }
        });
    }
}

From source file:com.keepe.plugins.cardio.CardIO.java

License:Open Source License

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {

    // TODO Auto-generated method stub
    this.callbackContext = callbackContext;

    try {/*w w  w.  ja v a 2  s .  c o  m*/
        // set configurations
        if (action.equals("scan")) {
            JSONObject config = args.getJSONObject(0);
            expiry = config.getBoolean("expiry");
            cvv = config.getBoolean("cvv");
            zip = config.getBoolean("zip");
            confirm = config.getBoolean("suppressConfirm");
            hideLogo = config.getBoolean("hideLogo");
            suppressManual = config.getBoolean("suppressManual");
            guideColor = Color.parseColor(config.getString("guideColor"));

            Intent scanIntent = new Intent(cordova.getActivity(), CardIOMain.class);
            cordova.getActivity().startActivity(scanIntent);

            PluginResult cardData = new PluginResult(PluginResult.Status.NO_RESULT);
            cardData.setKeepCallback(true);
            callbackContext.sendPluginResult(cardData);
            return true;
        } else if (action.equals("canScan")) {
            if (CardIOActivity.canReadCardWithCamera()) {
                callbackContext.success("PASS");
                return true;
            } else {
                callbackContext.error("FAIL");
                return false;
            }
        }
        return false;
    } catch (JSONException e) {
        e.printStackTrace();

        PluginResult res = new PluginResult(PluginResult.Status.JSON_EXCEPTION);
        callbackContext.sendPluginResult(res);
        return false;
    }

}

From source file:com.keepe.plugins.cardio.CardIO.java

License:Open Source License

@Override
public void onResume(boolean multitasking) {
    super.onResume(multitasking);

    // send plugin result if success
    JSONObject mImagepath = cardNumber;/*from  ww  w.j a va  2 s .  c  o m*/
    if (mImagepath != null) {
        PluginResult cardData = new PluginResult(PluginResult.Status.OK, cardNumber);
        cardData.setKeepCallback(false);
        callbackContext.sendPluginResult(cardData);
        cardNumber = null;
    } else {
        PluginResult cardData = new PluginResult(PluginResult.Status.NO_RESULT);
        cardData.setKeepCallback(false);
        callbackContext.sendPluginResult(cardData);
    }

}

From source file:com.knowledgecode.cordova.websocket.ConnectionTask.java

License:Apache License

@Override
public void execute(JSONArray args, CallbackContext ctx) {
    try {/*from w  w  w .  j a  v  a 2  s  .c  om*/
        WebSocketClient client = _factory.newWebSocketClient();

        int id = args.getInt(0);
        URI uri = new URI(args.getString(1));
        String protocol = args.getString(2);
        JSONObject options = args.getJSONObject(5);
        String origin = options.optString("origin", args.getString(3));
        String agent = options.optString("agent", args.getString(4));
        long maxConnectTime = options.optLong("maxConnectTime", MAX_CONNECT_TIME);

        client.setMaxTextMessageSize(options.optInt("maxTextMessageSize", MAX_TEXT_MESSAGE_SIZE));
        client.setMaxBinaryMessageSize(options.optInt("maxBinaryMessageSize", MAX_BINARY_MESSAGE_SIZE));
        if (protocol.length() > 0) {
            client.setProtocol(protocol);
        }
        if (origin.length() > 0) {
            client.setOrigin(origin);
        }
        if (agent.length() > 0) {
            client.setAgent(agent);
        }
        setCookie(client.getCookies(), uri.getHost());

        WebSocketGenerator gen = new WebSocketGenerator(id, ctx);

        gen.setOnOpenListener(new OnOpenListener() {
            @Override
            public void onOpen(int id, Connection conn) {
                _map.put(id, conn);
            }
        });
        gen.setOnCloseListener(new OnCloseListener() {
            @Override
            public void onClose(int id) {
                if (_map.indexOfKey(id) >= 0) {
                    _map.remove(id);
                }
            }
        });
        client.open(uri, gen, maxConnectTime, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        if (!ctx.isFinished()) {
            PluginResult result = new PluginResult(Status.ERROR);
            result.setKeepCallback(true);
            ctx.sendPluginResult(result);
        }
    }
}

From source file:com.knowledgecode.cordova.websocket.WebSocketGenerator.java

License:Apache License

/**
 * Send plugin result.//w  w w  .  ja  va2 s.co  m
 *
 * @param callbackString
 * @param keepCallback
 */
private void sendCallback(String callbackString, boolean keepCallback) {
    if (!_ctx.isFinished()) {
        PluginResult result = new PluginResult(Status.OK, callbackString);
        result.setKeepCallback(keepCallback);
        _ctx.sendPluginResult(result);
    }
}

From source file:com.likemag.cordova.inappbrowsercustom.InAppBrowser.java

License:Apache License

/**
 * Executes the request and returns PluginResult.
 *
 * @param action        The action to execute.
 * @param args          JSONArry of arguments for the plugin.
 * @param callbackId    The callback id used when calling back into JavaScript.
 * @return              A PluginResult object with a status and message.
 *//*from   w  w  w . j a v a  2  s  .c o m*/
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;

        //PDC TEAM 
        //Set close button caption and return option string
        String featureString = parseCloseButtonCaption(args.optString(2));

        //PDC TEAM
        //past to parseFeature function string without close button caption
        final HashMap<String, Boolean> features = parseFeature(featureString);

        Log.d(LOG_TAG, "target = " + target);

        this.cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String result = "";
                // SELF
                if (SELF.equals(target)) {
                    Log.d(LOG_TAG, "in self");
                    /* 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) {
                        try {
                            Method iuw = Config.class.getMethod("isUrlWhiteListed", String.class);
                            shouldAllowNavigation = (Boolean) iuw.invoke(null, url);
                        } catch (NoSuchMethodException e) {
                        } catch (IllegalAccessException e) {
                        } catch (InvocationTargetException e) {
                        }
                    }
                    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)) {
                        Log.d(LOG_TAG, "loading in webview");
                        webView.loadUrl(url);
                    }
                    //Load the dialer
                    else if (url.startsWith(WebView.SCHEME_TEL)) {
                        try {
                            Log.d(LOG_TAG, "loading in dialer");
                            Intent intent = new Intent(Intent.ACTION_DIAL);
                            intent.setData(Uri.parse(url));
                            cordova.getActivity().startActivity(intent);
                        } catch (android.content.ActivityNotFoundException e) {
                            LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
                        }
                    }
                    // load in InAppBrowser
                    else {
                        Log.d(LOG_TAG, "loading in InAppBrowser");
                        result = showWebPage(url, features);
                    }
                }
                // SYSTEM
                else if (SYSTEM.equals(target)) {
                    Log.d(LOG_TAG, "in system");
                    result = openExternal(url);
                }
                // BLANK - or anything else
                else {
                    Log.d(LOG_TAG, "in blank");
                    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 {
        return false;
    }
    return true;
}

From source file:com.macadamian.blinkup.BlinkUpPluginResult.java

License:Apache License

/*************************************
 * Generates JSON of our plugin results/*from   ww  w.j  a  v  a2s.co  m*/
 * and sends back to the callback
 *************************************/
public void sendResultsToCallback() {
    JSONObject resultJSON = new JSONObject();

    // set result status
    PluginResult.Status cordovaResultStatus;
    if (TextUtils.equals(mState, STATE_ERROR)) {
        cordovaResultStatus = PluginResult.Status.ERROR;
    } else {
        cordovaResultStatus = PluginResult.Status.OK;
    }

    try {
        resultJSON.put(ResultKeys.STATE.getKey(), mState);

        if (TextUtils.equals(mState, STATE_ERROR)) {
            resultJSON.put(ResultKeys.ERROR.getKey(), generateErrorJson());
        } else {
            resultJSON.put(ResultKeys.STATUS_CODE.getKey(), ("" + mStatusCode));
            if (mHasDeviceInfo) {
                resultJSON.put(ResultKeys.DEVICE_INFO.getKey(), generateDeviceInfoJson());
            }
        }
    } catch (JSONException e) {
        // don't want endless loop calling ourselves so just log error (don't send to callback)
        Log.e(TAG, "", e);
    }

    PluginResult pluginResult = new PluginResult(cordovaResultStatus, resultJSON.toString());
    pluginResult.setKeepCallback(true); // uses same BlinkUpPlugin object across calls, so need to keep callback
    BlinkUpPlugin.getCallbackContext().sendPluginResult(pluginResult);
}

From source file:com.manueldeveloper.SpeechRecognizer.java

License:Apache License

private void sendResults() {
    if (this.speechRecognizerCallbackContext != null) {
        PluginResult result = new PluginResult(PluginResult.Status.OK, new JSONArray(this.results));
        result.setKeepCallback(false);
        this.speechRecognizerCallbackContext.sendPluginResult(result);
    }/*from w w  w .j  a v  a 2  s. c  om*/
}