Example usage for org.apache.cordova PluginResult PluginResult

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

Introduction

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

Prototype

public PluginResult(Status status, List<PluginResult> multipartMessages) 

Source Link

Usage

From source file:com.creare.notifications.Notifications.java

License:Apache License

/**
 * Builds and shows a native Android prompt dialog with given title, message, buttons.
 * This dialog only shows up to 3 buttons.  Any labels after that will be ignored.
 * The following results are returned to the JavaScript callback identified by callbackId:
 *     buttonIndex         Index number of the button selected
 *     input1            The text entered in the prompt dialog box
 *
 * @param message           The message the dialog should display
 * @param title             The title of the dialog
 * @param buttonLabels      A comma separated list of button labels (Up to 3 buttons)
 * @param callbackContext   The callback context.
 *///  w  ww  .  j av  a  2  s  .  com
public synchronized void prompt(final String message, final String title, final JSONArray buttonLabels,
        final String defaultText, final CallbackContext callbackContext) {

    final CordovaInterface cordova = this.cordova;

    Runnable runnable = new Runnable() {
        public void run() {
            final EditText promptInput = new EditText(cordova.getActivity());
            promptInput.setHint(defaultText);
            AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
            dlg.setMessage(message);
            dlg.setTitle(title);
            dlg.setCancelable(false);

            dlg.setView(promptInput);

            final JSONObject result = new JSONObject();

            // First button
            if (buttonLabels.length() > 0) {
                try {
                    dlg.setNegativeButton(buttonLabels.getString(0), new AlertDialog.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            try {
                                result.put("buttonIndex", 1);
                                result.put("input1",
                                        promptInput.getText().toString().trim().length() == 0 ? defaultText
                                                : promptInput.getText());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
                        }
                    });
                } catch (JSONException e) {
                }
            }

            // Second button
            if (buttonLabels.length() > 1) {
                try {
                    dlg.setNeutralButton(buttonLabels.getString(1), new AlertDialog.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            try {
                                result.put("buttonIndex", 2);
                                result.put("input1",
                                        promptInput.getText().toString().trim().length() == 0 ? defaultText
                                                : promptInput.getText());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
                        }
                    });
                } catch (JSONException e) {
                }
            }

            // Third button
            if (buttonLabels.length() > 2) {
                try {
                    dlg.setPositiveButton(buttonLabels.getString(2), new AlertDialog.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            try {
                                result.put("buttonIndex", 3);
                                result.put("input1",
                                        promptInput.getText().toString().trim().length() == 0 ? defaultText
                                                : promptInput.getText());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
                        }
                    });
                } catch (JSONException e) {
                }
            }
            dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
                public void onCancel(DialogInterface dialog) {
                    dialog.dismiss();
                    try {
                        result.put("buttonIndex", 0);
                        result.put("input1", promptInput.getText().toString().trim().length() == 0 ? defaultText
                                : promptInput.getText());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
                }
            });

            changeTextDirection(dlg);
        };
    };
    this.cordova.getActivity().runOnUiThread(runnable);
}

From source file:com.crittercism.plugin.CDVCrittercism.java

License:Apache License

private boolean executeGetTransactionValue(String action, final JSONArray args, CallbackContext callbackContext)
        throws JSONException {
    // Executing task in foreground so that call is faster given the user may expect a synchronous response
    final String transaction = args.getString(0);
    final int transactionValue = Crittercism.getTransactionValue(transaction);
    callbackContext.sendPluginResult(new PluginResult(Status.OK, transactionValue));
    return true;/*from   ww w.  ja va  2  s.  c om*/
}

From source file:com.darktalker.cordova.screenshot.Screenshot.java

License:Open Source License

private void saveScreenshot(Bitmap bitmap, String format, String fileName, Integer quality) {
    try {/*from www.java 2 s  .c o  m*/
        File folder = new File(Environment.getExternalStorageDirectory(), "Pictures");
        if (!folder.exists()) {
            folder.mkdirs();
        }

        File f = new File(folder, fileName + "." + format);

        FileOutputStream fos = new FileOutputStream(f);
        if (format.equals("png")) {
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        } else if (format.equals("jpg")) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality == null ? 100 : quality, fos);
        }
        JSONObject jsonRes = new JSONObject();
        jsonRes.put("filePath", f.getAbsolutePath());
        PluginResult result = new PluginResult(PluginResult.Status.OK, jsonRes);
        mCallbackContext.sendPluginResult(result);

        scanPhoto(f.getAbsolutePath());
        fos.close();
    } catch (JSONException e) {
        mCallbackContext.error(e.getMessage());

    } catch (IOException e) {
        mCallbackContext.error(e.getMessage());

    }
}

From source file:com.darktalker.cordova.screenshot.Screenshot.java

License:Open Source License

private void getScreenshotAsURI(Bitmap bitmap, int quality) {
    try {//w  w  w .j  a  va 2  s . c om
        ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream();

        if (bitmap.compress(CompressFormat.JPEG, quality, jpeg_data)) {
            byte[] code = jpeg_data.toByteArray();
            byte[] output = Base64.encode(code, Base64.NO_WRAP);
            String js_out = new String(output);
            js_out = "data:image/jpeg;base64," + js_out;
            JSONObject jsonRes = new JSONObject();
            jsonRes.put("URI", js_out);
            PluginResult result = new PluginResult(PluginResult.Status.OK, jsonRes);
            mCallbackContext.sendPluginResult(result);

            js_out = null;
            output = null;
            code = null;
        }

        jpeg_data = null;

    } catch (JSONException e) {
        mCallbackContext.error(e.getMessage());

    } catch (Exception e) {
        mCallbackContext.error(e.getMessage());

    }
}

From source file:com.donler.plugin.easemob.Easemob.java

License:Apache License

private void dealGetMessages(JSONArray args) {
    final JSONArray _args = args;

    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            try {
                String chatType = _args.getString(0);
                String target = _args.getString(1);
                EMConversation conversation = EMChatManager.getInstance().getConversation(target);
                List<EMMessage> messages;
                if (_args.length() < 3) {
                    // 
                    messages = conversation.getAllMessages();
                } else {
                    final String startMsgId = _args.getString(2);
                    if (chatType.equals("group")) {
                        // 
                        messages = conversation.loadMoreGroupMsgFromDB(startMsgId, pagesize);
                    } else {
                        // sdk20db
                        // startMsgIdpagesizemessages
                        // sdkappmessages
                        messages = conversation.loadMoreMsgFromDB(startMsgId, pagesize);
                    }/*www  .j a  v  a  2 s  .c o  m*/
                }
                // 
                conversation.resetUnreadMsgCount();
                JSONArray mJSONArray = new JSONArray();
                for (int i = 0; i < messages.size(); i++) {
                    JSONObject message = messageToJson(messages.get(i));
                    mJSONArray.put(message);
                }
                PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, mJSONArray);
                emchatCallbackContext.sendPluginResult(pluginResult);
            } catch (JSONException e) {
                e.printStackTrace();
                emchatCallbackContext.error("");
            }
        }

    });

}

From source file:com.doylestowncoder.plugin.mobileaccessibility.MobileAccessibility.java

License:Apache License

protected void sendMobileAccessibilityStatusChangedCallback() {
    if (this.mCallbackContext != null) {
        PluginResult result = new PluginResult(PluginResult.Status.OK, getMobileAccessibilityStatus());
        result.setKeepCallback(true);//from ww w  .  j ava 2s .co  m
        this.mCallbackContext.sendPluginResult(result);
    }
}

From source file:com.dtworkshop.inappcrossbrowser.InAppChromeClient.java

License:Apache License

/**
 * Tell the client to display a prompt dialog to the user.
 * If the client returns true, WebView will assume that the client will
 * handle the prompt dialog and call the appropriate JsPromptResult method.
 *
 * The prompt bridge provided for the InAppBrowser is capable of executing any
 * oustanding callback belonging to the InAppBrowser plugin. Care has been
 * taken that other callbacks cannot be triggered, and that no other code
 * execution is possible./*from ww  w  .j  av a 2s  . c o  m*/
 *
 * To trigger the bridge, the prompt default value should be of the form:
 *
 * gap-iab://<callbackId>
 *
 * where <callbackId> is the string id of the callback to trigger (something
 * like "InAppBrowser0123456789")
 *
 * If present, the prompt message is expected to be a JSON-encoded value to
 * pass to the callback. A JSON_EXCEPTION is returned if the JSON is invalid.
 *
 * @param view
 * @param url
 * @param message
 * @param defaultValue
 * @param result
 */
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
        JsPromptResult result) {
    // See if the prompt string uses the 'gap-iab' protocol. If so, the remainder should be the id of a callback to execute.
    if (defaultValue != null && defaultValue.startsWith("gap")) {
        if (defaultValue.startsWith("gap-iab://")) {
            PluginResult scriptResult;
            String scriptCallbackId = defaultValue.substring(10);
            if (scriptCallbackId.startsWith("InAppBrowser")) {
                if (message == null || message.length() == 0) {
                    scriptResult = new PluginResult(PluginResult.Status.OK, new JSONArray());
                } else {
                    try {
                        scriptResult = new PluginResult(PluginResult.Status.OK, new JSONArray(message));
                    } catch (JSONException e) {
                        scriptResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage());
                    }
                }
                this.webView.sendPluginResult(scriptResult, scriptCallbackId);
                result.confirm("");
                return true;
            }
        } else {
            // Anything else with a gap: prefix should get this message
            LOG.w(LOG_TAG, "InAppBrowser does not support Cordova API calls: " + url + " " + defaultValue);
            result.cancel();
            return true;
        }
    }
    return false;
}

From source file:com.dtworkshop.inappcrossbrowser.WebViewBrowser.java

License:Apache License

/**
 * Executes the request and returns PluginResult.
 *
 * @param action        The action to execute.
 * @param args          JSONArry of arguments for the plugin.
 * @return              A PluginResult object with a status and message.
 *///from ww  w  . j  a  v a  2s .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 {
                            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);
                }
                // perso a3d HORIZONTAL
                else if (BLANKH.equals(target)) {
                    Log.d(LOG_TAG, "in blank horizontal");
                    result = showWebPage(url, features);
                }
                // 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.dtworkshop.inappcrossbrowser.WebViewBrowser.java

License:Apache License

/**
 * Create a new plugin result and send it back to JavaScript
 *
 * @param obj a JSONObject contain event payload information
 * @param status the status code to return to the JavaScript environment
 */// w  w w  .j  av  a2 s.  c  o  m
protected void sendUpdate(JSONObject obj, boolean keepCallback, PluginResult.Status status) {
    if (callbackContext != null) {
        PluginResult result = new PluginResult(status, obj);
        result.setKeepCallback(keepCallback);
        callbackContext.sendPluginResult(result);
        if (!keepCallback) {
            callbackContext = null;
        }
    }
}

From source file:com.dtz.plugins.azurehubnotification.AzureHubNotification.java

License:Apache License

protected void sendNotificationCallback(CallbackContext callbackContext, String result, Status status) {
    PluginResult progressResult = new PluginResult(status, result);
    progressResult.setKeepCallback(true);
    callbackContext.sendPluginResult(progressResult);
}