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.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 ww. j  a  v  a 2 s . c  om
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.localytics.phonegap.LocalyticsPlugin.java

License:BSD License

@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext)
        throws JSONException {
    if (action.equals("integrate")) {
        String localyticsKey = (args.length() == 1 ? args.getString(0) : null);
        Localytics.integrate(cordova.getActivity().getApplicationContext(), localyticsKey);
        callbackContext.success();// w w  w.j av  a2s . co  m
        return true;
    } else if (action.equals("upload")) {
        Localytics.upload();
        callbackContext.success();
        return true;
    } else if (action.equals("autoIntegrate")) {
        /* App-key is read from meta-data LOCALYTICS_APP_KEY in AndroidManifest */
        Application app = cordova.getActivity().getApplication();
        app.registerActivityLifecycleCallbacks(
                new LocalyticsActivityLifecycleCallbacks(app.getApplicationContext()));
        callbackContext.success();
        return true;
    } else if (action.equals("openSession")) {
        Localytics.openSession();
        callbackContext.success();
        return true;
    } else if (action.equals("closeSession")) {
        Localytics.closeSession();
        callbackContext.success();
        return true;
    } else if (action.equals("tagEvent")) {
        if (args.length() == 3) {
            String name = args.getString(0);
            if (name != null && name.length() > 0) {
                JSONObject attributes = null;
                if (!args.isNull(1)) {
                    attributes = args.getJSONObject(1);
                }
                HashMap<String, String> a = null;
                if (attributes != null && attributes.length() > 0) {
                    a = new HashMap<String, String>();
                    Iterator<?> keys = attributes.keys();
                    while (keys.hasNext()) {
                        String key = (String) keys.next();
                        String value = attributes.getString(key);
                        a.put(key, value);
                    }
                }
                int customerValueIncrease = args.getInt(2);
                Localytics.tagEvent(name, a, customerValueIncrease);
                callbackContext.success();
            } else {
                callbackContext.error("Expected non-empty name argument.");
            }
        } else {
            callbackContext.error("Expected three arguments.");
        }
        return true;
    } else if (action.equals("tagScreen")) {
        String name = args.getString(0);
        if (name != null && name.length() > 0) {
            Localytics.tagScreen(name);
            callbackContext.success();
        } else {
            callbackContext.error("Expected non-empty name argument.");
        }
        return true;
    } else if (action.equals("setCustomDimension")) {
        if (args.length() == 2) {
            int index = args.getInt(0);
            String value = null;
            if (!args.isNull(1)) {
                value = args.getString(1);
            }
            Localytics.setCustomDimension(index, value);
            callbackContext.success();
        } else {
            callbackContext.error("Expected two arguments.");
        }
        return true;
    } else if (action.equals("getCustomDimension")) {
        final int index = args.getInt(0);
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                String value = Localytics.getCustomDimension(index);
                callbackContext.success(value);
            }
        });
        return true;
    } else if (action.equals("setOptedOut")) {
        boolean enabled = args.getBoolean(0);
        Localytics.setOptedOut(enabled);
        callbackContext.success();
        return true;
    } else if (action.equals("isOptedOut")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                boolean enabled = Localytics.isOptedOut();
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, enabled));
            }
        });
        return true;
    } else if (action.equals("setProfileAttribute")) {
        if (args.length() == 3) {
            String errorString = null;

            String attributeName = args.getString(0);
            Object attributeValue = args.get(1);
            String scope = args.getString(2);

            if (attributeValue instanceof Integer) {
                Localytics.setProfileAttribute(attributeName, (Integer) attributeValue, getProfileScope(scope));
            } else if (attributeValue instanceof String) {
                Localytics.setProfileAttribute(attributeName, (String) attributeValue, getProfileScope(scope));
            } else if (attributeValue instanceof Date) {
                Localytics.setProfileAttribute(attributeName, (Date) attributeValue, getProfileScope(scope));
            } else if (attributeValue instanceof JSONArray) {
                JSONArray array = (JSONArray) attributeValue;
                Object item = getInitialItem(array);
                if (item instanceof Integer) {
                    long[] longs = buildLongArray(array);
                    if (longs != null) {
                        Localytics.setProfileAttribute(attributeName, longs, getProfileScope(scope));
                    } else {
                        errorString = ERROR_INVALID_ARRAY;
                    }
                } else if (item instanceof String) {
                    if (parseISO8601Date((String) item) != null) {
                        Date[] dates = buildDateArray(array);
                        if (dates != null) {
                            Localytics.addProfileAttributesToSet(attributeName, dates, getProfileScope(scope));
                        } else {
                            errorString = ERROR_INVALID_ARRAY;
                        }
                    } else {
                        String[] strings = buildStringArray(array);
                        if (strings != null) {
                            Localytics.addProfileAttributesToSet(attributeName, strings,
                                    getProfileScope(scope));
                        } else {
                            errorString = ERROR_INVALID_ARRAY;
                        }
                    }
                }
            } else {
                errorString = ERROR_UNSUPPORTED_TYPE;
            }

            if (errorString != null) {
                callbackContext.error(errorString);
            } else {
                callbackContext.success();
            }
        } else {
            callbackContext.error("Expected three arguments.");
        }
        return true;
    } else if (action.equals("addProfileAttributesToSet")) {
        if (args.length() == 3) {
            String errorString = null;

            String attributeName = args.getString(0);
            Object attributeValue = args.get(1);
            String scope = args.getString(2);

            if (attributeValue instanceof JSONArray) {
                JSONArray array = (JSONArray) attributeValue;
                Object item = getInitialItem(array);
                if (item instanceof Integer) {
                    long[] longs = buildLongArray(array);
                    if (longs != null) {
                        Localytics.addProfileAttributesToSet(attributeName, longs, getProfileScope(scope));
                    } else {
                        errorString = ERROR_INVALID_ARRAY;
                    }
                } else if (item instanceof String) {
                    // Check if date string first
                    if (parseISO8601Date((String) item) != null) {
                        Date[] dates = buildDateArray(array);
                        if (dates != null) {
                            Localytics.addProfileAttributesToSet(attributeName, dates, getProfileScope(scope));
                        } else {
                            errorString = ERROR_INVALID_ARRAY;
                        }
                    } else {
                        String[] strings = buildStringArray(array);
                        if (strings != null) {
                            Localytics.addProfileAttributesToSet(attributeName, strings,
                                    getProfileScope(scope));
                        } else {
                            errorString = ERROR_INVALID_ARRAY;
                        }
                    }
                }
            } else {
                errorString = ERROR_UNSUPPORTED_TYPE;
            }

            if (errorString != null) {
                callbackContext.error(errorString);
            } else {
                callbackContext.success();
            }
        } else {
            callbackContext.error("Expected three arguments.");
        }
        return true;
    } else if (action.equals("removeProfileAttributesFromSet")) {
        if (args.length() == 3) {
            String errorString = null;

            String attributeName = args.getString(0);
            Object attributeValue = args.get(1);
            String scope = args.getString(2);
            if (attributeValue instanceof JSONArray) {
                JSONArray array = (JSONArray) attributeValue;
                Object item = getInitialItem(array);
                if (item instanceof Integer) {
                    long[] longs = buildLongArray(array);
                    if (longs != null) {
                        Localytics.removeProfileAttributesFromSet(attributeName, longs, getProfileScope(scope));
                    } else {
                        errorString = ERROR_INVALID_ARRAY;
                    }
                } else if (item instanceof String) {
                    if (parseISO8601Date((String) item) != null) {
                        Date[] dates = buildDateArray(array);
                        if (dates != null) {
                            Localytics.addProfileAttributesToSet(attributeName, dates, getProfileScope(scope));
                        } else {
                            errorString = ERROR_INVALID_ARRAY;
                        }
                    } else {
                        String[] strings = buildStringArray(array);
                        if (strings != null) {
                            Localytics.addProfileAttributesToSet(attributeName, strings,
                                    getProfileScope(scope));
                        } else {
                            errorString = ERROR_INVALID_ARRAY;
                        }
                    }
                }
            } else {
                errorString = ERROR_UNSUPPORTED_TYPE;
            }

            if (errorString != null) {
                callbackContext.error(errorString);
            } else {
                callbackContext.success();
            }
        } else {
            callbackContext.error("Expected three arguments.");
        }
        return true;
    } else if (action.equals("incrementProfileAttribute")) {
        if (args.length() == 3) {
            String attributeName = args.getString(0);
            long incrementValue = args.getLong(1);
            String scope = args.getString(2);

            Localytics.incrementProfileAttribute(attributeName, incrementValue, getProfileScope(scope));
        } else {
            callbackContext.error("Expected three arguments.");
        }
        return true;
    } else if (action.equals("decrementProfileAttribute")) {
        if (args.length() == 3) {
            String attributeName = args.getString(0);
            long decrementValue = args.getLong(1);
            String scope = args.getString(2);

            Localytics.decrementProfileAttribute(attributeName, decrementValue, getProfileScope(scope));
        } else {
            callbackContext.error("Expected three arguments.");
        }
        return true;
    } else if (action.equals("deleteProfileAttribute")) {
        if (args.length() == 2) {
            String attributeName = args.getString(0);
            String scope = args.getString(1);

            Localytics.deleteProfileAttribute(attributeName, getProfileScope(scope));
        } else {
            callbackContext.error("Expected three arguments.");
        }
        return true;
    } else if (action.equals("setIdentifier")) {
        if (args.length() == 2) {
            String key = args.getString(0);
            if (key != null && key.length() > 0) {
                String value = null;
                if (!args.isNull(1)) {
                    value = args.getString(1);
                }
                Localytics.setIdentifier(key, value);
                callbackContext.success();
            } else {
                callbackContext.error("Expected non-empty key argument.");
            }
        } else {
            callbackContext.error("Expected two arguments.");
        }
        return true;
    } else if (action.equals("setCustomerId")) {
        String id = null;
        if (!args.isNull(0)) {
            id = args.getString(0);
        }
        Localytics.setCustomerId(id);
        callbackContext.success();
        return true;
    } else if (action.equals("setCustomerFullName")) {
        String fullName = null;
        if (!args.isNull(0)) {
            fullName = args.getString(0);
        }
        Localytics.setCustomerFullName(fullName);
        callbackContext.success();
        return true;
    } else if (action.equals("setCustomerFirstName")) {
        String firstName = null;
        if (!args.isNull(0)) {
            firstName = args.getString(0);
        }
        Localytics.setCustomerFirstName(firstName);
        callbackContext.success();
        return true;
    } else if (action.equals("setCustomerLastName")) {
        String lastName = null;
        if (!args.isNull(0)) {
            lastName = args.getString(0);
        }
        Localytics.setCustomerLastName(lastName);
        callbackContext.success();
        return true;
    } else if (action.equals("setCustomerEmail")) {
        String email = null;
        if (!args.isNull(0)) {
            email = args.getString(0);
        }
        Localytics.setCustomerEmail(email);
        callbackContext.success();
        return true;
    } else if (action.equals("setLocation")) {
        if (args.length() == 2) {
            Location location = new Location("");
            location.setLatitude(args.getDouble(0));
            location.setLongitude(args.getDouble(1));

            Localytics.setLocation(location);
            callbackContext.success();
        } else {
            callbackContext.error("Expected two arguments.");
        }
        return true;
    } else if (action.equals("registerPush")) {
        String senderId = null;

        try {
            PackageManager pm = cordova.getActivity().getPackageManager();
            ApplicationInfo ai = pm.getApplicationInfo(cordova.getActivity().getPackageName(),
                    PackageManager.GET_META_DATA);
            Bundle metaData = ai.metaData;
            senderId = metaData.getString(PROP_SENDER_ID);
        } catch (PackageManager.NameNotFoundException e) {
            //No-op
        }

        Localytics.registerPush(senderId);
        callbackContext.success();
        return true;
    } else if (action.equals("setPushDisabled")) {
        boolean enabled = args.getBoolean(0);
        Localytics.setPushDisabled(enabled);
        callbackContext.success();
        return true;
    } else if (action.equals("isPushDisabled")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                boolean enabled = Localytics.isPushDisabled();
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, enabled));
            }
        });
        return true;
    } else if (action.equals("setTestModeEnabled")) {
        boolean enabled = args.getBoolean(0);
        Localytics.setTestModeEnabled(enabled);
        callbackContext.success();
        return true;
    } else if (action.equals("isTestModeEnabled")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                boolean enabled = Localytics.isTestModeEnabled();
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, enabled));
            }
        });
        return true;
    } else if (action.equals("setInAppMessageDismissButtonImageWithName")) {
        //No-op
        return true;
    } else if (action.equals("setInAppMessageDismissButtonLocation")) {
        //No-op
        return true;
    } else if (action.equals("getInAppMessageDismissButtonLocation")) {
        //No-op
        return true;
    } else if (action.equals("triggerInAppMessage")) {
        //No-op
        return true;
    } else if (action.equals("dismissCurrentInAppMessage")) {
        //No-op
        return true;
    } else if (action.equals("setLoggingEnabled")) {
        boolean enabled = args.getBoolean(0);
        Localytics.setLoggingEnabled(enabled);
        callbackContext.success();
        return true;
    } else if (action.equals("isLoggingEnabled")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                boolean enabled = Localytics.isLoggingEnabled();
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, enabled));
            }
        });
        return true;
    } else if (action.equals("setSessionTimeoutInterval")) {
        int seconds = args.getInt(0);
        Localytics.setSessionTimeoutInterval(seconds);
        callbackContext.success();
        return true;
    } else if (action.equals("getSessionTimeoutInterval")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                long timeout = Localytics.getSessionTimeoutInterval();
                callbackContext.success(Long.valueOf(timeout).toString());
            }
        });
        return true;
    } else if (action.equals("getInstallId")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                String result = Localytics.getInstallId();
                callbackContext.success(result);
            }
        });
        return true;
    } else if (action.equals("getAppKey")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                String result = Localytics.getAppKey();
                callbackContext.success(result);
            }
        });

        return true;
    } else if (action.equals("getLibraryVersion")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                String result = Localytics.getLibraryVersion();
                callbackContext.success(result);
            }
        });
        return true;
    }
    return false;
}

From source file:com.luhuiguo.cordova.voice.VoiceHandler.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 used when calling back into JavaScript.
 * @return              A PluginResult object with a status and message.
 */// ww w. java  2s. c  o  m
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    CordovaResourceApi resourceApi = webView.getResourceApi();
    PluginResult.Status status = PluginResult.Status.OK;
    String result = "";

    if (action.equals("startRecording")) {
        String target = args.getString(1);
        String fileUriStr;
        try {
            Uri targetUri = resourceApi.remapUri(Uri.parse(target));
            fileUriStr = targetUri.toString();
        } catch (IllegalArgumentException e) {
            fileUriStr = target;
        }
        this.startRecording(args.getString(0), VoiceHandler.stripFileProtocol(fileUriStr));
    } else if (action.equals("stopRecording")) {
        this.stopRecording(args.getString(0));
    } else if (action.equals("startPlaying")) {
        String target = args.getString(1);
        String fileUriStr;
        try {
            Uri targetUri = resourceApi.remapUri(Uri.parse(target));
            fileUriStr = targetUri.toString();
        } catch (IllegalArgumentException e) {
            fileUriStr = target;
        }
        this.startPlaying(args.getString(0), VoiceHandler.stripFileProtocol(fileUriStr));
    } else if (action.equals("seekTo")) {
        this.seekTo(args.getString(0), args.getInt(1));
    } else if (action.equals("pausePlaying")) {
        this.pausePlaying(args.getString(0));
    } else if (action.equals("stopPlaying")) {
        this.stopPlaying(args.getString(0));
    } else if (action.equals("setVolume")) {
        try {
            this.setVolume(args.getString(0), Float.parseFloat(args.getString(1)));
        } catch (NumberFormatException nfe) {
            //no-op
        }
    } else if (action.equals("getCurrentPosition")) {
        float f = this.getCurrentPosition(args.getString(0));
        callbackContext.sendPluginResult(new PluginResult(status, f));
        return true;
    } else if (action.equals("getPower")) {
        float f = this.getPower(args.getString(0));
        callbackContext.sendPluginResult(new PluginResult(status, f));
        return true;
    } else if (action.equals("getDuration")) {
        float f = this.getDuration(args.getString(0), args.getString(1));
        callbackContext.sendPluginResult(new PluginResult(status, f));
        return true;
    } else if (action.equals("create")) {
        String id = args.getString(0);
        String src = VoiceHandler.stripFileProtocol(args.getString(1));
        VoicePlayer voice = new VoicePlayer(this, id, src);
        this.players.put(id, voice);
    } else if (action.equals("release")) {
        boolean b = this.release(args.getString(0));
        callbackContext.sendPluginResult(new PluginResult(status, b));
        return true;
    } else { // Unrecognized action.
        return false;
    }

    callbackContext.sendPluginResult(new PluginResult(status, result));

    return true;
}

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

License:Apache License

/*************************************
 * Generates JSON of our plugin results/*from w  w w  . j av  a 2s.c o 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.macdonst.ftpclient.FtpClient.java

License:BSD License

/**
  * Executes the request and returns PluginResult.
  *//from   w ww .  ja va2 s  .  com
  * @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.
  */
@Override
public boolean execute(final String action, final JSONArray args, final CallbackContext callbackContext) {

    final PluginResult.Status status = PluginResult.Status.OK;
    final JSONArray result = new JSONArray();

    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                String filename = args.getString(0);
                URL url = new URL(args.getString(1));

                if (action.equals("get")) {
                    get(filename, url);
                } else if (action.equals("put")) {
                    put(filename, url);
                }
                callbackContext.sendPluginResult(new PluginResult(status, result));
            } catch (JSONException e) {
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
            } catch (MalformedURLException e) {
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.MALFORMED_URL_EXCEPTION));
            } catch (IOException e) {
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION));
            }
        }
    });
    t.start();
    return true;
}

From source file:com.manu.videoplayer.NewActivity.java

License:BSD License

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    PluginResult.Status status = PluginResult.Status.OK;
    String result = "";

    try {/*  ww  w .jav a2 s  . c o m*/
        if (action.equals("playVideo")) {
            playVideo(args.getString(0), args.getInt(1), args.getInt(2));
        } else {
            status = PluginResult.Status.INVALID_ACTION;
        }
        callbackContext.sendPluginResult(new PluginResult(status, result));
    } catch (JSONException e) {
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
    } catch (IOException e) {
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION));
    }
    return true;
}

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);//from ww w  .j a  va 2s.c  o m
        this.speechRecognizerCallbackContext.sendPluginResult(result);
    }
}

From source file:com.manueldeveloper.VolumeButtonsListener.java

License:Apache License

/**
*    Method which sends back a new PluginResult to Javascript
*
*   @param      info: JSONObject object with the information to send back
*   @param      keepCallback: boolean which indicates if there will be more results
* 
*    @date      27/02/2014/*w w  w.j a va  2 s .  c om*/
*    @version   0.0.1
*    @author   ManuelDeveloper(manueldeveloper@gmail.com) 
*/
private void sendSignal(JSONObject info, boolean keepCallback) {
    if (this.volumeCallbackContext != null) {
        PluginResult result = new PluginResult(PluginResult.Status.OK, info);
        result.setKeepCallback(keepCallback);
        this.volumeCallbackContext.sendPluginResult(result);
    }
}

From source file:com.marianhello.cordova.bgloc.BackgroundGpsPlugin.java

License:Apache License

private void handleMessage(Intent msg) {
    Bundle data = msg.getExtras();/*from  w w  w .j  a  v a 2  s  .c  o m*/
    switch (data.getInt(Constant.COMMAND, 0)) {
    case Constant.UPDATE_PROGRESS:
        try {
            JSONObject location = new JSONObject(data.getString(Constant.DATA));
            PluginResult result = new PluginResult(PluginResult.Status.OK, location);
            result.setKeepCallback(true);
            callbackContext.sendPluginResult(result);
            Log.d(TAG, "Sending plugin result");
        } catch (JSONException e) {
            Log.w(TAG, "Error converting message to json");
        }
        break;
    default:
        break;
    }
}

From source file:com.mattrayner.vuforia.VuforiaPlugin.java

public void stopVuforia(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    // JSON we will send back to Cordova
    JSONObject json = new JSONObject();

    // Is Vuforia sterts?
    if (vuforiaStarted) {
        Log.d(LOGTAG, "Stopping plugin");

        // Stop Vuforia
        sendAction(DISMISS_ACTION);/*from  ww  w  .j  a v a 2s  .  c o  m*/
        vuforiaStarted = false;

        json.put("success", "true");
    } else {
        Log.d(LOGTAG, "Cannot stop the plugin because it wasn't started");

        json.put("success", "false");
        json.put("message", "No Vuforia session running");
    }

    // Send an OK result back to Cordova
    PluginResult result = new PluginResult(PluginResult.Status.OK, json);
    callback.sendPluginResult(result);
}