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.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  w w w.jav  a 2  s . c o  m
        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.intel.GooglePlayGamesPlugin.java

License:Open Source License

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

    String intentAction = "";
    // Check for compatible Google Play services APK
    if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this.cordova.getActivity()) != 0) {
        // Google Play Services is missing, return error
        Log.e(TAG, "Google Play Services are unavailable");
        callbackContext.error(GGSError.UNAVAILABLE);
        return true;
    } else {/*from   ww  w. ja v  a2s .c  o m*/
        Log.d(TAG, "** Google Play Services are available **");
    }

    if (playGamesService == null) {
        playGamesService = new GooglePlayGamesService();
    }
    cb = callbackContext;

    if (action.equals("authenticate")) {
        if (isSignedIn()) {
            cb.sendPluginResult(new PluginResult(PluginResult.Status.OK, "-1"));
            return true;
        }
        getApiClient();//Make the connection here
        intentAction = PLAY_SERVICES_LOGIN;
        Context context = this.cordova.getActivity().getApplicationContext(); //
        Intent intent = new Intent(context, GooglePlayGamesService.class);
        intent.putExtra(PLAY_SERVICES_MESSAGE, intentAction);
        cordova.startActivityForResult(this, intent, SIGNIN_ACTIVITY);
        return true;
    } else if (action.equals("logout")) {
        if (mGoogleApiClient != null || mGoogleApiClient.isConnected()) {
            getApiClient().disconnect();
        }

        cb.sendPluginResult(new PluginResult(PluginResult.Status.OK, "-1"));
        return true;
    } else if (action.equals("achievements")) {
        if (!isSignedIn()) {
            cb.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "1"));
            return true;
        }
        cordova.startActivityForResult(this, Games.Achievements.getAchievementsIntent(getApiClient()),
                REQUEST_ACHIEVEMENTS);
        return true;
    } else if (action.equals("addAchievement")) {
        if (!isSignedIn()) {
            cb.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "1"));
            return true;
        }
        if (args.length() == 0)
            return false;
        String achievementId = "";
        try {
            achievementId = args.get(0).toString();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            return false;
        }
        Games.Achievements.unlock(getApiClient(), achievementId);
        cb.sendPluginResult(new PluginResult(PluginResult.Status.OK, "-1"));
        return true;
    } else if (action.equals("incrementAchievement")) {
        if (!isSignedIn()) {
            cb.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "1"));
            return true;
        }
        if (args.length() == 0)
            return false;
        String achievementId = "";
        int value = 0;
        try {
            achievementId = args.get(0).toString();
            value = Integer.parseInt(args.get(1).toString());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            return false;
        }
        Games.Achievements.increment(getApiClient(), achievementId, value);
        cb.sendPluginResult(new PluginResult(PluginResult.Status.OK, "-1"));
        return true;
    } else if (action.equals("showLeaderboard")) {
        if (!isSignedIn()) {
            cb.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "1"));
            return true;
        }
        if (args.length() == 0)
            return false;
        String leaderboardId = "";
        try {
            leaderboardId = args.get(0).toString();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            return false;
        }
        cordova.startActivityForResult(this,
                Games.Leaderboards.getLeaderboardIntent(getApiClient(), leaderboardId), REQUEST_LEADERBOARD);
    } else if (action.equals("updateLeaderboardScore")) {
        if (!isSignedIn()) {
            cb.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "1"));
            return true;
        }
        if (args.length() == 0)
            return false;
        String leaderboardId = "";
        Long score;
        try {
            leaderboardId = args.get(0).toString();
            score = Long.parseLong(args.get(1).toString());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            return false;
        }
        Games.Leaderboards.submitScore(getApiClient(), leaderboardId, score);
        cb.sendPluginResult(new PluginResult(PluginResult.Status.OK, "-1"));
        return true;
    } else if (action.equals("connect")) {
        cb.sendPluginResult(new PluginResult(PluginResult.Status.OK, "-1"));
        return true;
    }

    return true;
}

From source file:com.intel.GooglePlayGamesPlugin.java

License:Open Source License

public void onActivityResult(int requestCode, int resultCode, Intent data) {

    cb.sendPluginResult(new PluginResult(PluginResult.Status.OK, Integer.toString(resultCode)));
}

From source file:com.ionicframework.lovescanning967442.wxapi.WXEntryActivity.java

License:Open Source License

@Override
public void onResp(BaseResp resp) {
    switch (resp.errCode) {
    case BaseResp.ErrCode.ERR_OK:
        if (resp instanceof SendAuth.Resp) {
            JSONObject object = new JSONObject();
            try {
                object.put("code", ((SendAuth.Resp) resp).token);
                object.put("state", ((SendAuth.Resp) resp).state);
            } catch (JSONException e) {
                e.printStackTrace();/*from www .j a va 2s . com*/
            }
            PluginResult res = new PluginResult(PluginResult.Status.OK, object);
            WeChat.currentCallbackContext.sendPluginResult(res);
        } else
            WeChat.currentCallbackContext.success();
        break;
    case BaseResp.ErrCode.ERR_USER_CANCEL:
        WeChat.currentCallbackContext.error(WeChat.ERR_USER_CANCEL);
        break;
    case BaseResp.ErrCode.ERR_AUTH_DENIED:
        WeChat.currentCallbackContext.error(WeChat.ERR_AUTH_DENIED);
        break;
    case BaseResp.ErrCode.ERR_SENT_FAILED:
        WeChat.currentCallbackContext.error(WeChat.ERR_SENT_FAILED);
        break;
    case BaseResp.ErrCode.ERR_UNSUPPORT:
        WeChat.currentCallbackContext.error(WeChat.ERR_UNSUPPORT);
        break;
    case BaseResp.ErrCode.ERR_COMM:
        WeChat.currentCallbackContext.error(WeChat.ERR_COMM);
        break;
    default:
        WeChat.currentCallbackContext.error(WeChat.ERR_UNKNOWN);
        break;
    }
    finish();
}

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
 *//*www  .j  av  a 2  s  . c o  m*/
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);
    }
}

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  .jav  a 2s .co 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.jomendezdev.cordova.admob.AdMobAds.java

License:Open Source License

/**
 * Parses the show ad input parameters and runs the show ad action on the UI thread.
 * //from   w  w  w  .  ja  v a 2s  .  co  m
 * @param inputs The JSONArray representing input parameters. This function expects the first object in the array to be a JSONObject with the input
 *          parameters.
 * @return A PluginResult representing whether or not an ad was requested succcessfully. Listen for onReceiveAd() and onFailedToReceiveAd() callbacks to see
 *         if an ad was successfully retrieved.
 */
private PluginResult executeShowBannerAd(final boolean show, final CallbackContext callbackContext) {
    if (adView == null) {
        return new PluginResult(Status.ERROR, "adView is null, call createBannerView first.");
    }

    cordova.getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (show == isBannerVisible) {
                // no change

            } else if (show) {
                if (adView.getParent() != null) {
                    ((ViewGroup) adView.getParent()).removeView(adView);
                }

                if (isBannerOverlap) {
                    RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(
                            RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

                    if (isOffsetStatusBar) {
                        int titleBarHeight = 0;
                        Rect rectangle = new Rect();
                        Window window = AdMobAds.this.cordova.getActivity().getWindow();
                        window.getDecorView().getWindowVisibleDisplayFrame(rectangle);

                        if (isBannerAtTop) {
                            if (rectangle.top == 0) {
                                int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
                                titleBarHeight = contentViewTop - rectangle.top;
                            }
                            params2.topMargin = titleBarHeight;

                        } else {
                            if (rectangle.top > 0) {
                                int contentViewBottom = window.findViewById(Window.ID_ANDROID_CONTENT)
                                        .getBottom();
                                titleBarHeight = contentViewBottom - rectangle.bottom;
                            }
                            params2.bottomMargin = titleBarHeight;
                        }

                    } else if (isBannerAtTop) {
                        params2.addRule(RelativeLayout.ALIGN_PARENT_TOP);

                    } else {
                        params2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                    }

                    adViewLayout.addView(adView, params2);
                    adViewLayout.bringToFront();

                } else {
                    ViewGroup parentView = (ViewGroup) webView.getParent();
                    if (isBannerAtTop) {
                        parentView.addView(adView, 0);
                    } else {
                        parentView.addView(adView);
                    }
                    parentView.bringToFront();
                }

                adView.setVisibility(View.VISIBLE);
                isBannerVisible = true;

            } else {
                adView.setVisibility(View.GONE);
                isBannerVisible = false;
            }

            if (callbackContext != null) {
                callbackContext.success();
            }
        }
    });
    return null;
}

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;/* w  ww  .ja 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.klick.plugins.listviewalert.ListViewAlert.java

License:Apache License

public void loadList(final JSONArray thelist, final CallbackContext callbackContext) {
    final CordovaInterface cordova = this.cordova;
    Runnable runnable = new Runnable() {
        public void run() {
            List<String> list = new ArrayList<String>();
            // we start with index 1 because index 0 is the title
            for (int x = 1; x < thelist.length(); x++) {
                try {
                    list.add(thelist.getString(x));
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }//from   ww  w.j  av a2 s .co m
            }
            CharSequence[] items = list.toArray(new CharSequence[list.size()]);
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    new ContextThemeWrapper(cordova.getActivity(), android.R.style.Theme_Holo_Dialog));
            try {
                builder.setTitle(thelist.getString(0));
                // builder.setMessage( "This is a hardcoded message to try whether or not this is feasible!");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } // index 0 contains the title
            builder.setItems(items, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
                    dialog.dismiss();
                    // we +1 to item because item starts from 0, but from
                    // thelist[0], that was the title...
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, item + 1));
                    //callbackContext.sendPluginResult(pluginResult)
                }
            });
            AlertDialog alert = builder.create();
            alert.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
            alert.show();
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
}

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

License:Apache License

/**
 * Send plugin result./*ww  w .j av  a  2  s  . c o  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);
    }
}