Search in sources :

Example 26 with PluginResult

use of org.apache.cordova.PluginResult in project phonegap-plugin-push by phonegap.

the class PushPlugin method sendEvent.

public static void sendEvent(JSONObject _json) {
    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, _json);
    pluginResult.setKeepCallback(true);
    if (pushContext != null) {
        pushContext.sendPluginResult(pluginResult);
    }
}
Also used : PluginResult(org.apache.cordova.PluginResult)

Example 27 with PluginResult

use of org.apache.cordova.PluginResult in project phonegap-plugin-push by phonegap.

the class PushPlugin method execute.

@Override
public boolean execute(final String action, final JSONArray data, final CallbackContext callbackContext) {
    Log.v(LOG_TAG, "execute: action=" + action);
    gWebView = this.webView;
    if (INITIALIZE.equals(action)) {
        cordova.getThreadPool().execute(new Runnable() {

            public void run() {
                pushContext = callbackContext;
                JSONObject jo = null;
                Log.v(LOG_TAG, "execute: data=" + data.toString());
                SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(COM_ADOBE_PHONEGAP_PUSH, Context.MODE_PRIVATE);
                String senderID = null;
                try {
                    jo = data.getJSONObject(0).getJSONObject(ANDROID);
                    Log.v(LOG_TAG, "execute: jo=" + jo.toString());
                    senderID = jo.getString(SENDER_ID);
                    Log.v(LOG_TAG, "execute: senderID=" + senderID);
                    registration_id = InstanceID.getInstance(getApplicationContext()).getToken(senderID, GCM);
                    if (!"".equals(registration_id)) {
                        JSONObject json = new JSONObject().put(REGISTRATION_ID, registration_id);
                        Log.v(LOG_TAG, "onRegistered: " + json.toString());
                        JSONArray topics = jo.optJSONArray(TOPICS);
                        subscribeToTopics(topics, registration_id);
                        PushPlugin.sendEvent(json);
                    } else {
                        callbackContext.error("Empty registration ID received from GCM");
                        return;
                    }
                } catch (JSONException e) {
                    Log.e(LOG_TAG, "execute: Got JSON Exception " + e.getMessage());
                    callbackContext.error(e.getMessage());
                } catch (IOException e) {
                    Log.e(LOG_TAG, "execute: Got JSON Exception " + e.getMessage());
                    callbackContext.error(e.getMessage());
                }
                if (jo != null) {
                    SharedPreferences.Editor editor = sharedPref.edit();
                    try {
                        editor.putString(ICON, jo.getString(ICON));
                    } catch (JSONException e) {
                        Log.d(LOG_TAG, "no icon option");
                    }
                    try {
                        editor.putString(ICON_COLOR, jo.getString(ICON_COLOR));
                    } catch (JSONException e) {
                        Log.d(LOG_TAG, "no iconColor option");
                    }
                    boolean clearBadge = jo.optBoolean(CLEAR_BADGE, false);
                    if (clearBadge) {
                        setApplicationIconBadgeNumber(getApplicationContext(), 0);
                    }
                    editor.putBoolean(SOUND, jo.optBoolean(SOUND, true));
                    editor.putBoolean(VIBRATE, jo.optBoolean(VIBRATE, true));
                    editor.putBoolean(CLEAR_BADGE, clearBadge);
                    editor.putBoolean(CLEAR_NOTIFICATIONS, jo.optBoolean(CLEAR_NOTIFICATIONS, true));
                    editor.putBoolean(FORCE_SHOW, jo.optBoolean(FORCE_SHOW, false));
                    editor.putString(SENDER_ID, senderID);
                    editor.putString(MESSAGE_KEY, jo.optString(MESSAGE_KEY));
                    editor.putString(TITLE_KEY, jo.optString(TITLE_KEY));
                    editor.commit();
                }
                if (!gCachedExtras.isEmpty()) {
                    Log.v(LOG_TAG, "sending cached extras");
                    synchronized (gCachedExtras) {
                        Iterator<Bundle> gCachedExtrasIterator = gCachedExtras.iterator();
                        while (gCachedExtrasIterator.hasNext()) {
                            sendExtras(gCachedExtrasIterator.next());
                        }
                    }
                    gCachedExtras.clear();
                }
            }
        });
    } else if (UNREGISTER.equals(action)) {
        cordova.getThreadPool().execute(new Runnable() {

            public void run() {
                try {
                    SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(COM_ADOBE_PHONEGAP_PUSH, Context.MODE_PRIVATE);
                    JSONArray topics = data.optJSONArray(0);
                    if (topics != null && !"".equals(registration_id)) {
                        unsubscribeFromTopics(topics, registration_id);
                    } else {
                        InstanceID.getInstance(getApplicationContext()).deleteInstanceID();
                        Log.v(LOG_TAG, "UNREGISTER");
                        // Remove shared prefs
                        SharedPreferences.Editor editor = sharedPref.edit();
                        editor.remove(SOUND);
                        editor.remove(VIBRATE);
                        editor.remove(CLEAR_BADGE);
                        editor.remove(CLEAR_NOTIFICATIONS);
                        editor.remove(FORCE_SHOW);
                        editor.remove(SENDER_ID);
                        editor.commit();
                    }
                    callbackContext.success();
                } catch (IOException e) {
                    Log.e(LOG_TAG, "execute: Got JSON Exception " + e.getMessage());
                    callbackContext.error(e.getMessage());
                }
            }
        });
    } else if (FINISH.equals(action)) {
        callbackContext.success();
    } else if (HAS_PERMISSION.equals(action)) {
        cordova.getThreadPool().execute(new Runnable() {

            public void run() {
                JSONObject jo = new JSONObject();
                try {
                    jo.put("isEnabled", PermissionUtils.hasPermission(getApplicationContext(), "OP_POST_NOTIFICATION"));
                    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, jo);
                    pluginResult.setKeepCallback(true);
                    callbackContext.sendPluginResult(pluginResult);
                } catch (UnknownError e) {
                    callbackContext.error(e.getMessage());
                } catch (JSONException e) {
                    callbackContext.error(e.getMessage());
                }
            }
        });
    } else if (SET_APPLICATION_ICON_BADGE_NUMBER.equals(action)) {
        cordova.getThreadPool().execute(new Runnable() {

            public void run() {
                Log.v(LOG_TAG, "setApplicationIconBadgeNumber: data=" + data.toString());
                try {
                    setApplicationIconBadgeNumber(getApplicationContext(), data.getJSONObject(0).getInt(BADGE));
                } catch (JSONException e) {
                    callbackContext.error(e.getMessage());
                }
                callbackContext.success();
            }
        });
    } else if (CLEAR_ALL_NOTIFICATIONS.equals(action)) {
        cordova.getThreadPool().execute(new Runnable() {

            public void run() {
                Log.v(LOG_TAG, "clearAllNotifications");
                clearAllNotifications();
                callbackContext.success();
            }
        });
    } else if (SUBSCRIBE.equals(action)) {
        // Subscribing for a topic
        cordova.getThreadPool().execute(new Runnable() {

            public void run() {
                try {
                    String topic = data.getString(0);
                    subscribeToTopic(topic, registration_id);
                    callbackContext.success();
                } catch (JSONException e) {
                    callbackContext.error(e.getMessage());
                } catch (IOException e) {
                    callbackContext.error(e.getMessage());
                }
            }
        });
    } else if (UNSUBSCRIBE.equals(action)) {
        // un-subscribing for a topic
        cordova.getThreadPool().execute(new Runnable() {

            public void run() {
                try {
                    String topic = data.getString(0);
                    unsubscribeFromTopic(topic, registration_id);
                    callbackContext.success();
                } catch (JSONException e) {
                    callbackContext.error(e.getMessage());
                } catch (IOException e) {
                    callbackContext.error(e.getMessage());
                }
            }
        });
    } else {
        Log.e(LOG_TAG, "Invalid action : " + action);
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION));
        return false;
    }
    return true;
}
Also used : JSONObject(org.json.JSONObject) PluginResult(org.apache.cordova.PluginResult) SharedPreferences(android.content.SharedPreferences) JSONArray(org.json.JSONArray) Iterator(java.util.Iterator) JSONException(org.json.JSONException) IOException(java.io.IOException)

Example 28 with PluginResult

use of org.apache.cordova.PluginResult in project phonegap-facebook-plugin by Wizcorp.

the class App method execute.

/**
     * 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.
     * @return                  A PluginResult object with a status and message.
     */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    PluginResult.Status status = PluginResult.Status.OK;
    String result = "";
    try {
        if (action.equals("clearCache")) {
            this.clearCache();
        } else if (action.equals("show")) {
            // This gets called from JavaScript onCordovaReady to show the webview.
            // I recommend we change the name of the Message as spinner/stop is not
            // indicative of what this actually does (shows the webview).
            cordova.getActivity().runOnUiThread(new Runnable() {

                public void run() {
                    webView.postMessage("spinner", "stop");
                }
            });
        } else if (action.equals("loadUrl")) {
            this.loadUrl(args.getString(0), args.optJSONObject(1));
        } else if (action.equals("cancelLoadUrl")) {
        //this.cancelLoadUrl();
        } else if (action.equals("clearHistory")) {
            this.clearHistory();
        } else if (action.equals("backHistory")) {
            this.backHistory();
        } else if (action.equals("overrideButton")) {
            this.overrideButton(args.getString(0), args.getBoolean(1));
        } else if (action.equals("overrideBackbutton")) {
            this.overrideBackbutton(args.getBoolean(0));
        } else if (action.equals("exitApp")) {
            this.exitApp();
        }
        callbackContext.sendPluginResult(new PluginResult(status, result));
        return true;
    } catch (JSONException e) {
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
        return false;
    }
}
Also used : PluginResult(org.apache.cordova.PluginResult) JSONException(org.json.JSONException)

Example 29 with PluginResult

use of org.apache.cordova.PluginResult in project phonegap-facebook-plugin by Wizcorp.

the class PluginManager method execHelper.

private void execHelper(final String service, final String action, final String callbackId, final String rawArgs) {
    CordovaPlugin plugin = getPlugin(service);
    if (plugin == null) {
        Log.d(TAG, "exec() call to unknown plugin: " + service);
        PluginResult cr = new PluginResult(PluginResult.Status.CLASS_NOT_FOUND_EXCEPTION);
        app.sendPluginResult(cr, callbackId);
        return;
    }
    try {
        CallbackContext callbackContext = new CallbackContext(callbackId, app);
        long pluginStartTime = System.currentTimeMillis();
        boolean wasValidAction = plugin.execute(action, rawArgs, callbackContext);
        long duration = System.currentTimeMillis() - pluginStartTime;
        if (duration > SLOW_EXEC_WARNING_THRESHOLD) {
            Log.w(TAG, "THREAD WARNING: exec() call to " + service + "." + action + " blocked the main thread for " + duration + "ms. Plugin should use CordovaInterface.getThreadPool().");
        }
        if (!wasValidAction) {
            PluginResult cr = new PluginResult(PluginResult.Status.INVALID_ACTION);
            app.sendPluginResult(cr, callbackId);
        }
    } catch (JSONException e) {
        PluginResult cr = new PluginResult(PluginResult.Status.JSON_EXCEPTION);
        app.sendPluginResult(cr, callbackId);
    }
}
Also used : PluginResult(org.apache.cordova.PluginResult) CordovaPlugin(org.apache.cordova.CordovaPlugin) CallbackContext(org.apache.cordova.CallbackContext) JSONException(org.json.JSONException)

Example 30 with PluginResult

use of org.apache.cordova.PluginResult in project phonegap-facebook-plugin by Wizcorp.

the class ConnectPlugin method execute.

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals("login")) {
        Log.d(TAG, "login FB");
        // Get the permissions
        String[] arrayPermissions = new String[args.length()];
        for (int i = 0; i < args.length(); i++) {
            arrayPermissions[i] = args.getString(i);
        }
        List<String> permissions = null;
        if (arrayPermissions.length > 0) {
            permissions = Arrays.asList(arrayPermissions);
        }
        // Get the currently active session
        Session session = Session.getActiveSession();
        // Set a pending callback to cordova
        loginContext = callbackContext;
        PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
        pr.setKeepCallback(true);
        loginContext.sendPluginResult(pr);
        // Check if the active session is open
        if (checkActiveSession(session)) {
            // Reauthorize flow
            boolean publishPermissions = false;
            boolean readPermissions = false;
            // Figure out if this will be a read or publish reauthorize
            if (permissions == null) {
                // No permissions, read
                readPermissions = true;
            }
            // is being requested
            for (String permission : arrayPermissions) {
                if (isPublishPermission(permission)) {
                    publishPermissions = true;
                } else {
                    readPermissions = true;
                }
                // Break if we have a mixed bag, as this is an error
                if (publishPermissions && readPermissions) {
                    break;
                }
            }
            if (publishPermissions && readPermissions) {
                callbackContext.error("Cannot ask for both read and publish permissions.");
            } else {
                // Set up the new permissions request
                Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(cordova.getActivity(), permissions);
                // Set up the activity result callback to this class
                cordova.setActivityResultCallback(this);
                // Check for write permissions, the default is read (empty)
                if (publishPermissions) {
                    // Request new publish permissions
                    session.requestNewPublishPermissions(newPermissionsRequest);
                } else {
                    // Request new read permissions
                    session.requestNewReadPermissions(newPermissionsRequest);
                }
            }
        } else {
            // Initial login, build a new session open request.
            // - Create a new session and set the application ID
            session = new Session.Builder(cordova.getActivity()).setApplicationId(applicationId).build();
            // Set up the activity result callback to this class
            cordova.setActivityResultCallback(this);
            Session.setActiveSession(session);
            // - Create the request
            Session.OpenRequest openRequest = new Session.OpenRequest(cordova.getActivity());
            // - Set the permissions
            openRequest.setPermissions(permissions);
            // - Set the status change call back
            openRequest.setCallback(new Session.StatusCallback() {

                @Override
                public void call(Session session, SessionState state, Exception exception) {
                    onSessionStateChange(state, exception);
                }
            });
            // Can only ask for read permissions initially
            session.openForRead(openRequest);
        }
        return true;
    } else if (action.equals("logout")) {
        Session session = Session.getActiveSession();
        if (checkActiveSession(session)) {
            session.closeAndClearTokenInformation();
            userID = null;
            callbackContext.success();
        } else {
            if (session != null) {
                // Session was existing, but was not open
                callbackContext.error("Session not open.");
            } else {
                callbackContext.error("No valid session found, must call init and login before logout.");
            }
        }
        return true;
    } else if (action.equals("getLoginStatus")) {
        Session session = Session.getActiveSession();
        if (userID == null && Session.getActiveSession() != null && session.isOpened()) {
            // We have no userID but a valid session, so must update the user info
            // (Probably app was force stopped)
            final CallbackContext _callbackContext = callbackContext;
            getUserInfo(session, new GraphUserCallback() {

                @Override
                public void onCompleted(GraphUser user, Response response) {
                    // recursive call to generate the correct response JSON
                    if (response.getError() != null) {
                        _callbackContext.error(getFacebookRequestErrorResponse(response.getError()));
                    } else {
                        userID = user.getId();
                        _callbackContext.success(getResponse());
                    }
                }
            });
        } else {
            callbackContext.success(getResponse());
        }
        return true;
    } else if (action.equals("getAccessToken")) {
        Session session = Session.getActiveSession();
        if (checkActiveSession(session)) {
            callbackContext.success(session.getAccessToken());
        } else {
            if (session == null) {
                callbackContext.error("No valid session found, must call init and login before logout.");
            } else {
                // Session not open
                callbackContext.error("Session not open.");
            }
        }
        return true;
    } else if (action.equals("logEvent")) {
        if (args.length() == 0) {
            // Not enough parameters
            callbackContext.error("Invalid arguments");
            return true;
        }
        String eventName = args.getString(0);
        if (args.length() == 1) {
            logger.logEvent(eventName);
        } else {
            // Arguments is greater than 1
            JSONObject params = args.getJSONObject(1);
            Bundle parameters = new Bundle();
            Iterator<?> iterator = params.keys();
            while (iterator.hasNext()) {
                try {
                    // Try get a String
                    String key = (String) iterator.next();
                    String value = params.getString(key);
                    parameters.putString(key, value);
                } catch (Exception e) {
                    // Maybe it was an int
                    Log.w(TAG, "Type in AppEvent parameters was not String for key: " + (String) iterator.next());
                    try {
                        String key = (String) iterator.next();
                        int value = params.getInt(key);
                        parameters.putInt(key, value);
                    } catch (Exception e2) {
                        // Nope
                        Log.e(TAG, "Unsupported type in AppEvent parameters for key: " + (String) iterator.next());
                    }
                }
            }
            if (args.length() == 2) {
                logger.logEvent(eventName, parameters);
            }
            if (args.length() == 3) {
                double value = args.getDouble(2);
                logger.logEvent(eventName, value, parameters);
            }
        }
        callbackContext.success();
        return true;
    } else if (action.equals("logPurchase")) {
        /*
             * While calls to logEvent can be made to register purchase events,
             * there is a helper method that explicitly takes a currency indicator.
             */
        if (args.length() != 2) {
            callbackContext.error("Invalid arguments");
            return true;
        }
        int value = args.getInt(0);
        String currency = args.getString(1);
        logger.logPurchase(BigDecimal.valueOf(value), Currency.getInstance(currency));
        callbackContext.success();
        return true;
    } else if (action.equals("showDialog")) {
        Bundle collect = new Bundle();
        JSONObject params = null;
        try {
            params = args.getJSONObject(0);
        } catch (JSONException e) {
            params = new JSONObject();
        }
        final ConnectPlugin me = this;
        Iterator<?> iter = params.keys();
        while (iter.hasNext()) {
            String key = (String) iter.next();
            if (key.equals("method")) {
                try {
                    this.method = params.getString(key);
                } catch (JSONException e) {
                    Log.w(TAG, "Nonstring method parameter provided to dialog");
                }
            } else {
                try {
                    collect.putString(key, params.getString(key));
                } catch (JSONException e) {
                    // Need to handle JSON parameters
                    Log.w(TAG, "Nonstring parameter provided to dialog discarded");
                }
            }
        }
        this.paramBundle = new Bundle(collect);
        //The Share dialog prompts a person to publish an individual story or an Open Graph story to their timeline.
        //This does not require Facebook Login or any extended permissions, so it is the easiest way to enable sharing on web.
        boolean isShareDialog = this.method.equalsIgnoreCase("share") || this.method.equalsIgnoreCase("share_open_graph");
        //If is a Share dialog but FB app is not installed the WebDialog Builder fails. 
        //In Android all WebDialogs require a not null Session object.
        boolean canPresentShareDialog = isShareDialog && (FacebookDialog.canPresentShareDialog(me.cordova.getActivity(), FacebookDialog.ShareDialogFeature.SHARE_DIALOG));
        //Must be an active session when is not a Shared dialog or if the Share dialog cannot be presented.
        boolean requiresAnActiveSession = (!isShareDialog) || (!canPresentShareDialog);
        if (requiresAnActiveSession) {
            Session session = Session.getActiveSession();
            if (!checkActiveSession(session)) {
                callbackContext.error("No active session");
                return true;
            }
        }
        // Begin by sending a callback pending notice to Cordova
        showDialogContext = callbackContext;
        PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
        pr.setKeepCallback(true);
        showDialogContext.sendPluginResult(pr);
        // Setup callback context
        final OnCompleteListener dialogCallback = new OnCompleteListener() {

            @Override
            public void onComplete(Bundle values, FacebookException exception) {
                if (exception != null) {
                    handleError(exception, showDialogContext);
                } else {
                    handleSuccess(values);
                }
            }
        };
        if (this.method.equalsIgnoreCase("feed")) {
            Runnable runnable = new Runnable() {

                public void run() {
                    WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(me.cordova.getActivity(), Session.getActiveSession(), paramBundle)).setOnCompleteListener(dialogCallback).build();
                    feedDialog.show();
                }
            };
            cordova.getActivity().runOnUiThread(runnable);
        } else if (this.method.equalsIgnoreCase("apprequests")) {
            Runnable runnable = new Runnable() {

                public void run() {
                    WebDialog requestsDialog = (new WebDialog.RequestsDialogBuilder(me.cordova.getActivity(), Session.getActiveSession(), paramBundle)).setOnCompleteListener(dialogCallback).build();
                    requestsDialog.show();
                }
            };
            cordova.getActivity().runOnUiThread(runnable);
        } else if (isShareDialog) {
            if (canPresentShareDialog) {
                Runnable runnable = new Runnable() {

                    public void run() {
                        // Publish the post using the Share Dialog
                        FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(me.cordova.getActivity()).setName(paramBundle.getString("name")).setCaption(paramBundle.getString("caption")).setDescription(paramBundle.getString("description")).setLink(paramBundle.getString("href")).setPicture(paramBundle.getString("picture")).build();
                        uiHelper.trackPendingDialogCall(shareDialog.present());
                    }
                };
                this.trackingPendingCall = true;
                cordova.getActivity().runOnUiThread(runnable);
            } else {
                // Fallback. For example, publish the post using the Feed Dialog
                Runnable runnable = new Runnable() {

                    public void run() {
                        WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(me.cordova.getActivity(), Session.getActiveSession(), paramBundle)).setOnCompleteListener(dialogCallback).build();
                        feedDialog.show();
                    }
                };
                cordova.getActivity().runOnUiThread(runnable);
            }
        } else if (this.method.equalsIgnoreCase("send")) {
            Runnable runnable = new Runnable() {

                public void run() {
                    FacebookDialog.MessageDialogBuilder builder = new FacebookDialog.MessageDialogBuilder(me.cordova.getActivity());
                    if (paramBundle.containsKey("link"))
                        builder.setLink(paramBundle.getString("link"));
                    if (paramBundle.containsKey("caption"))
                        builder.setCaption(paramBundle.getString("caption"));
                    if (paramBundle.containsKey("name"))
                        builder.setName(paramBundle.getString("name"));
                    if (paramBundle.containsKey("picture"))
                        builder.setPicture(paramBundle.getString("picture"));
                    if (paramBundle.containsKey("description"))
                        builder.setDescription(paramBundle.getString("description"));
                    // Check for native FB Messenger application
                    if (builder.canPresent()) {
                        FacebookDialog dialog = builder.build();
                        dialog.present();
                    } else {
                        // Not found
                        trackingPendingCall = false;
                        String errMsg = "Messaging unavailable.";
                        Log.e(TAG, errMsg);
                        showDialogContext.error(errMsg);
                    }
                }

                ;
            };
            this.trackingPendingCall = true;
            cordova.getActivity().runOnUiThread(runnable);
        } else {
            callbackContext.error("Unsupported dialog method.");
        }
        return true;
    } else if (action.equals("graphApi")) {
        graphContext = callbackContext;
        PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
        pr.setKeepCallback(true);
        graphContext.sendPluginResult(pr);
        graphPath = args.getString(0);
        JSONArray arr = args.getJSONArray(1);
        final List<String> permissionsList = new ArrayList<String>();
        for (int i = 0; i < arr.length(); i++) {
            permissionsList.add(arr.getString(i));
        }
        boolean publishPermissions = false;
        boolean readPermissions = false;
        if (permissionsList.size() > 0) {
            for (String permission : permissionsList) {
                if (isPublishPermission(permission)) {
                    publishPermissions = true;
                } else {
                    readPermissions = true;
                }
                // Break if we have a mixed bag, as this is an error
                if (publishPermissions && readPermissions) {
                    break;
                }
            }
            if (publishPermissions && readPermissions) {
                graphContext.error("Cannot ask for both read and publish permissions.");
            } else {
                Session session = Session.getActiveSession();
                if (session.getPermissions().containsAll(permissionsList)) {
                    makeGraphCall();
                } else {
                    // Set up the new permissions request
                    Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(cordova.getActivity(), permissionsList);
                    // Set up the activity result callback to this class
                    cordova.setActivityResultCallback(this);
                    // Check for write permissions, the default is read (empty)
                    if (publishPermissions) {
                        // Request new publish permissions
                        session.requestNewPublishPermissions(newPermissionsRequest);
                    } else {
                        // Request new read permissions
                        session.requestNewReadPermissions(newPermissionsRequest);
                    }
                }
            }
        } else {
            makeGraphCall();
        }
        return true;
    }
    return false;
}
Also used : SessionState(com.facebook.SessionState) PluginResult(org.apache.cordova.PluginResult) GraphUserCallback(com.facebook.Request.GraphUserCallback) FacebookDialog(com.facebook.widget.FacebookDialog) FacebookException(com.facebook.FacebookException) CallbackContext(org.apache.cordova.CallbackContext) ArrayList(java.util.ArrayList) List(java.util.List) GraphUser(com.facebook.model.GraphUser) Bundle(android.os.Bundle) WebDialog(com.facebook.widget.WebDialog) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) FacebookOperationCanceledException(com.facebook.FacebookOperationCanceledException) JSONException(org.json.JSONException) FacebookServiceException(com.facebook.FacebookServiceException) FacebookException(com.facebook.FacebookException) FacebookDialogException(com.facebook.FacebookDialogException) FacebookAuthorizationException(com.facebook.FacebookAuthorizationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Response(com.facebook.Response) OnCompleteListener(com.facebook.widget.WebDialog.OnCompleteListener) JSONObject(org.json.JSONObject) Session(com.facebook.Session)

Aggregations

PluginResult (org.apache.cordova.PluginResult)45 JSONException (org.json.JSONException)19 JSONObject (org.json.JSONObject)15 IOException (java.io.IOException)6 JSONArray (org.json.JSONArray)6 Uri (android.net.Uri)4 FileNotFoundException (java.io.FileNotFoundException)4 AlertDialog (android.app.AlertDialog)3 DialogInterface (android.content.DialogInterface)3 Intent (android.content.Intent)3 TextView (android.widget.TextView)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 File (java.io.File)3 OutputStream (java.io.OutputStream)3 CallbackContext (org.apache.cordova.CallbackContext)3 CordovaInterface (org.apache.cordova.CordovaInterface)3 CordovaResourceApi (org.apache.cordova.CordovaResourceApi)3 NativeToJsMessageQueue (org.apache.cordova.NativeToJsMessageQueue)3 Test (org.junit.Test)3 SharedPreferences (android.content.SharedPreferences)2