Example usage for org.apache.cordova.api PluginResult PluginResult

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

Introduction

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

Prototype

public PluginResult(Status status) 

Source Link

Usage

From source file:BluetoothPlugin.java

License:Apache License

/**
 * Execute a bluetooth function/*from   w  w  w  .  java2  s . c o  m*/
 */
@Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
    PluginResult pluginResult = null;

    Log.d("BluetoothPlugin", "Action: " + action);

    if (ACTION_ENABLE.equals(action)) {
        // Check if bluetooth isn't disabled already
        if (!m_bluetoothAdapter.isEnabled()) {
            m_stateChanging = true;
            ctx.startActivityForResult(this, new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 1);
            while (m_stateChanging) {
            }
            ;
        }

        // Check if bluetooth is enabled now
        if (m_bluetoothAdapter.isEnabled()) {
            pluginResult = new PluginResult(PluginResult.Status.OK);
        } else {
            pluginResult = new PluginResult(PluginResult.Status.ERROR);
        }
    }
    // Want to disable bluetooth?
    else if (ACTION_DISABLE.equals(action)) {
        if (!m_bluetoothAdapter.disable() && m_bluetoothAdapter.isEnabled()) {
            pluginResult = new PluginResult(PluginResult.Status.ERROR);
        } else {
            pluginResult = new PluginResult(PluginResult.Status.OK);
        }

    } else if (ACTION_DISCOVERDEVICES.equals(action)) {
        m_discoveredDevices = new JSONArray();

        if (!m_bluetoothAdapter.startDiscovery()) {
            pluginResult = new PluginResult(PluginResult.Status.ERROR, "Unable to start discovery");
        } else {
            m_discovering = true;

            // Wait for discovery to finish
            while (m_discovering) {
            }

            Log.d("BluetoothPlugin", "DiscoveredDevices: " + m_discoveredDevices.length());

            pluginResult = new PluginResult(PluginResult.Status.OK, m_discoveredDevices);
        }
    }
    // Want to list UUIDs of a certain device
    else if (ACTION_GETUUIDS.equals(action)) {

        try {
            String address = args.getString(0);
            Log.d("BluetoothPlugin", "Listing UUIDs for: " + address);

            // Fetch UUIDs from bluetooth device
            BluetoothDevice bluetoothDevice = m_bluetoothAdapter.getRemoteDevice(address);
            Method m = bluetoothDevice.getClass().getMethod("fetchUuidsWithSdp");
            Log.d("BluetoothPlugin", "Method: " + m);
            m.invoke(bluetoothDevice);

            m_gettingUuids = true;

            while (m_gettingUuids) {
            }

            pluginResult = new PluginResult(PluginResult.Status.OK, m_gotUUIDs);

        } catch (Exception e) {
            Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage());

            pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage());
        }
    }
    // Connect to a given device & uuid endpoint
    else if (ACTION_CONNECT.equals(action)) {
        try {
            String address = args.getString(0);
            UUID uuid = UUID.fromString(args.getString(1));

            Log.d("BluetoothPlugin", "Connecting...");

            BluetoothDevice bluetoothDevice = m_bluetoothAdapter.getRemoteDevice(address);
            BluetoothSocket bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);

            bluetoothSocket.connect();

            m_bluetoothSockets.add(bluetoothSocket);
            int socketId = m_bluetoothSockets.indexOf(bluetoothSocket);

            pluginResult = new PluginResult(PluginResult.Status.OK, socketId);
        } catch (Exception e) {
            Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage());

            pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage());
        }
    } else if (ACTION_READ.equals(action)) {
        try {
            int socketId = args.getInt(0);

            BluetoothSocket bluetoothSocket = m_bluetoothSockets.get(socketId);
            InputStream inputStream = bluetoothSocket.getInputStream();

            char[] buffer = new char[128];
            for (int i = 0; i < buffer.length; i++) {
                buffer[i] = (char) inputStream.read();
            }

            //Log.d( "BluetoothPlugin", "Buffer: " + String.valueOf(buffer) );
            pluginResult = new PluginResult(PluginResult.Status.OK, String.valueOf(buffer));
        } catch (Exception e) {
            Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage());

            pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage());
        }
    } else if (ACTION_DISCONNECT.equals(action)) {
        try {
            int socketId = args.getInt(0);

            // Fetch socket & close it
            BluetoothSocket bluetoothSocket = m_bluetoothSockets.get(socketId);
            bluetoothSocket.close();

            // Remove socket from internal list
            m_bluetoothSockets.remove(socketId);

            // Everything went fine...
            pluginResult = new PluginResult(PluginResult.Status.OK);
        } catch (Exception e) {
            Log.e("BluetoothPlugin", e.toString() + " / " + e.getMessage());

            pluginResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage());
        }
    }

    return pluginResult;
}

From source file:com.apptech.first.cordova.plugins.push.pushnotifications.PushNotifications.java

License:Open Source License

private PluginResult internalRegister(JSONArray data, String callbackId) {
    JSONObject params = null;// www .j  a v  a  2 s . c o  m
    try {
        params = data.getJSONObject(0);
    } catch (JSONException e) {
        e.printStackTrace();
        return new PluginResult(Status.ERROR);
    }

    try {
        mPushManager = new PushManager(cordova.getActivity(), params.getString("appid"),
                params.getString("projectid"));
    } catch (JSONException e) {
        e.printStackTrace();
        return new PluginResult(Status.ERROR);
    }

    try {
        if (loggedStart) {
            mPushManager.onStartup(cordova.getActivity(), false);
        } else {
            mPushManager.onStartup(cordova.getActivity(), true);
            loggedStart = true;
        }
    } catch (java.lang.RuntimeException e) {
        e.printStackTrace();
        return new PluginResult(Status.ERROR);
    }

    checkMessage(cordova.getActivity().getIntent());

    callbackIds.put("registerDevice", callbackId);

    PluginResult result = new PluginResult(Status.NO_RESULT);
    result.setKeepCallback(true);
    return result;
}

From source file:com.apptech.first.cordova.plugins.push.pushnotifications.PushNotifications.java

License:Open Source License

private PluginResult internalUnregister(JSONArray data, String callbackId) {
    callbackIds.put("unregisterDevice", callbackId);
    PluginResult result = new PluginResult(Status.NO_RESULT);
    result.setKeepCallback(true);/*w  ww.  j  a  va 2s  .  c  o  m*/

    try {
        GCMRegistrar.unregister(cordova.getActivity());
    } catch (Exception e) {
        return new PluginResult(Status.ERROR);
    }

    return result;
}

From source file:com.apptech.first.cordova.plugins.push.pushnotifications.PushNotifications.java

License:Open Source License

private PluginResult internalSendLocation(JSONArray data, String callbackId) {
    if (mPushManager == null) {
        return new PluginResult(Status.ERROR);
    }/*from ww w.  j  a va 2s . c o  m*/

    JSONObject params = null;
    try {
        params = data.getJSONObject(0);
    } catch (JSONException e) {
        e.printStackTrace();
        return new PluginResult(Status.ERROR);
    }

    double lat = 0;
    double lon = 0;

    try {
        lat = params.getDouble("lat");
        lon = params.getDouble("lon");
    } catch (JSONException e) {
        e.printStackTrace();
        return new PluginResult(Status.ERROR);
    }

    Location location = new Location("");
    location.setLatitude(lat);
    location.setLongitude(lon);
    PushManager.sendLocation(cordova.getActivity(), location);

    return new PluginResult(Status.OK);
}

From source file:com.apptech.first.cordova.plugins.push.pushnotifications.PushNotifications.java

License:Open Source License

private PluginResult internalSendTags(JSONArray data, String callbackId) {
    if (mPushManager == null) {
        return new PluginResult(Status.ERROR);
    }/*from  w w w .java  2s.  c o m*/

    JSONObject params;
    try {
        params = data.getJSONObject(0);
    } catch (JSONException e) {
        e.printStackTrace();
        return new PluginResult(Status.ERROR);
    }

    @SuppressWarnings("unchecked")
    Iterator<String> nameItr = params.keys();
    Map<String, Object> paramsMap = new HashMap<String, Object>();
    while (nameItr.hasNext()) {
        try {
            String name = nameItr.next();
            paramsMap.put(name, params.get(name));
        } catch (JSONException e) {
            e.printStackTrace();
            return new PluginResult(Status.ERROR);
        }
    }

    try {
        Map<String, String> skippedTags = PushManager.sendTagsFromBG(cordova.getActivity(), paramsMap);

        JSONObject skippedTagsObj = new JSONObject();
        for (String tagName : skippedTags.keySet()) {
            skippedTags.put(tagName, skippedTags.get(tagName));
        }

        return new PluginResult(Status.OK, skippedTagsObj);
    } catch (PushWooshException e) {
        e.printStackTrace();
        return new PluginResult(Status.ERROR);
    }
}

From source file:com.apptech.first.cordova.plugins.push.pushnotifications.PushNotifications.java

License:Open Source License

@Override
public PluginResult execute(String action, JSONArray data, String callbackId) {
    Log.d("PushNotifications", "Plugin Called");

    if (REGISTER.equals(action)) {
        return internalRegister(data, callbackId);
    }/*w w w .  j av  a2s . c  om*/

    if (UNREGISTER.equals(action)) {
        return internalUnregister(data, callbackId);
    }

    if (SET_TAGS.equals(action)) {
        return internalSendTags(data, callbackId);
    }

    if (SEND_LOCATION.equals(action)) {
        return internalSendLocation(data, callbackId);
    }

    if (START_GEO_PUSHES.equals(action)) {
        if (mPushManager == null) {
            return new PluginResult(Status.ERROR);
        }

        mPushManager.startTrackingGeoPushes();
        return new PluginResult(Status.OK);
    }

    if (STOP_GEO_PUSHES.equals(action)) {
        if (mPushManager == null) {
            return new PluginResult(Status.ERROR);
        }

        mPushManager.stopTrackingGeoPushes();
        return new PluginResult(Status.OK);
    }

    if (CREATE_LOCAL_NOTIFICATION.equals(action)) {
        JSONObject params = null;
        try {
            params = data.getJSONObject(0);
        } catch (JSONException e) {
            e.printStackTrace();
            return new PluginResult(Status.ERROR);
        }

        try {
            //config params: {msg:"message", seconds:30, userData:"optional"}
            String message = params.getString("msg");
            Integer seconds = params.getInt("seconds");
            if (message == null || seconds == null)
                return new PluginResult(Status.ERROR);

            String userData = params.getString("userData");

            Bundle extras = new Bundle();
            if (userData != null)
                extras.putString("u", userData);

            PushManager.scheduleLocalNotification(cordova.getActivity(), message, extras, seconds);
        } catch (JSONException e) {
            e.printStackTrace();
            return new PluginResult(Status.ERROR);
        }

        return new PluginResult(Status.OK);
    }

    if (CLEAR_LOCAL_NOTIFICATION.equals(action)) {
        PushManager.clearLocalNotifications(cordova.getActivity());
        return new PluginResult(Status.OK);
    }

    if ("setMultiNotificationMode".equals(action)) {
        if (mPushManager == null) {
            return new PluginResult(Status.ERROR);
        }

        mPushManager.setMultiNotificationMode();
        return new PluginResult(Status.OK);
    }

    if ("setSingleNotificationMode".equals(action)) {
        if (mPushManager == null) {
            return new PluginResult(Status.ERROR);
        }

        mPushManager.setSimpleNotificationMode();
        return new PluginResult(Status.OK);
    }

    if ("setSoundType".equals(action)) {
        if (mPushManager == null) {
            return new PluginResult(Status.ERROR);
        }

        JSONObject params = null;
        try {
            Integer type = (Integer) data.get(0);
            if (type == null)
                return new PluginResult(Status.ERROR);

            mPushManager.setSoundNotificationType(SoundType.fromInt(type));
        } catch (Exception e) {
            e.printStackTrace();
            return new PluginResult(Status.ERROR);
        }

        return new PluginResult(Status.OK);
    }

    if ("setVibrateType".equals(action)) {
        if (mPushManager == null) {
            return new PluginResult(Status.ERROR);
        }

        JSONObject params = null;
        try {
            Integer type = (Integer) data.get(0);
            if (type == null)
                return new PluginResult(Status.ERROR);

            mPushManager.setVibrateNotificationType(VibrateType.fromInt(type));
        } catch (Exception e) {
            e.printStackTrace();
            return new PluginResult(Status.ERROR);
        }

        return new PluginResult(Status.OK);
    }

    if ("setLightScreenOnNotification".equals(action)) {
        if (mPushManager == null) {
            return new PluginResult(Status.ERROR);
        }

        JSONObject params = null;
        try {
            boolean type = (boolean) data.getBoolean(0);
            mPushManager.setLightScreenOnNotification(type);
        } catch (Exception e) {
            e.printStackTrace();
            return new PluginResult(Status.ERROR);
        }

        return new PluginResult(Status.OK);
    }

    if ("sendGoalAchieved".equals(action)) {
        if (mPushManager == null) {
            return new PluginResult(Status.ERROR);
        }

        JSONObject params = null;
        try {
            params = data.getJSONObject(0);
        } catch (JSONException e) {
            e.printStackTrace();
            return new PluginResult(Status.ERROR);
        }

        try {
            //config params: {goal:"goalName", count:30}
            String goal = params.getString("goal");
            if (goal == null)
                return new PluginResult(Status.ERROR);

            Integer count = null;
            if (params.has("count"))
                count = params.getInt("count");

            mPushManager.sendGoalAchieved(cordova.getActivity(), goal, count);
        } catch (Exception e) {
            e.printStackTrace();
            return new PluginResult(Status.ERROR);
        }

        return new PluginResult(Status.OK);
    }

    Log.d("DirectoryListPlugin", "Invalid action : " + action + " passed");
    return new PluginResult(Status.INVALID_ACTION);
}

From source file:com.baroq.pico.google.PlayServices.java

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

    try {// ww  w  .j  a v  a 2  s  .  c o m
        if (!ACTION_SETUP.equals(action) && !ACTION_SIGNIN.equals(action)
                && (null == mHelper || !mHelper.isConnected())) {
            callbackContext.error("Please setup and signin to use PlayServices plugin");
            return false;
        }
        if (ACTION_SETUP.equals(action)) {
            int l = data.length();
            if (0 == l) {
                callbackContext.error("Expecting at least 1 parameter for action: " + action);
                return false;
            }
            clientTypes = data.getInt(0);
            String[] extraScopes = new String[l - 1];
            for (int i = 1; i < l; i++) {
                extraScopes[i - 1] = data.getString(i);
            }
            setup(clientTypes, extraScopes, callbackContext);
            PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
            pluginResult.setKeepCallback(true);
            callbackContext.sendPluginResult(pluginResult);
        } else if (ACTION_SIGNIN.equals(action)) {
            mHelper.beginUserInitiatedSignIn();
            callbackContext.success();
        } else if (ACTION_SIGNOUT.equals(action)) {
            signout();
            callbackContext.success();
        } else if (ACTION_AS_MAX_KEYS.equals(action)) {
            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK,
                    mHelper.getAppStateClient().getMaxNumKeys());
            pluginResult.setKeepCallback(false);
            callbackContext.sendPluginResult(pluginResult);
        } else if (ACTION_AS_MAX_SIZE.equals(action)) {
            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK,
                    mHelper.getAppStateClient().getMaxStateSize());
            pluginResult.setKeepCallback(false);
            callbackContext.sendPluginResult(pluginResult);
        } else if (ACTION_AS_DEL.equals(action)) {
            int key = data.getInt(0);
            mHelper.getAppStateClient().deleteState(this, key);
            callbackContext.success();
        } else if (ACTION_AS_LIST.equals(action)) {
            mHelper.getAppStateClient().listStates(this);
            callbackContext.success();
        } else if (ACTION_AS_LOAD.equals(action)) {
            int key = data.getInt(0);
            mHelper.getAppStateClient().loadState(this, key);
            callbackContext.success();
        } else if (ACTION_AS_RESOLVE.equals(action)) {
            int key = data.getInt(0);
            String resolvedVersion = data.getString(1);
            String value = data.getString(2);
            mHelper.getAppStateClient().resolveState(this, key, resolvedVersion, value.getBytes());
            callbackContext.success();
        } else if (ACTION_AS_UPDATE.equals(action)) {
            int key = data.getInt(0);
            String value = data.getString(1);
            mHelper.getAppStateClient().updateState(key, value.getBytes());
            callbackContext.success();
        } else if (ACTION_AS_UPDATE_NOW.equals(action)) {
            int key = data.getInt(0);
            String value = data.getString(1);
            mHelper.getAppStateClient().updateStateImmediate(this, key, value.getBytes());
            callbackContext.success();
        } else if (ACTION_GAME_SHOW_ACHIEVEMENTS.equals(action)) {
            cordova.startActivityForResult((CordovaPlugin) this,
                    mHelper.getGamesClient().getAchievementsIntent(), RC_UNUSED);
            callbackContext.success();
        } else if (ACTION_GAME_SHOW_LEADERBOARDS.equals(action)) {
            cordova.startActivityForResult((CordovaPlugin) this,
                    mHelper.getGamesClient().getAllLeaderboardsIntent(), RC_UNUSED);
            callbackContext.success();
        } else if (ACTION_GAME_SHOW_LEADERBOARD.equals(action)) {
            String id = data.getString(0);
            cordova.startActivityForResult((CordovaPlugin) this,
                    mHelper.getGamesClient().getLeaderboardIntent(id), RC_UNUSED);
            callbackContext.success();
        } else if (ACTION_GAME_INCR_ACHIEVEMENT.equals(action)) {
            String id = data.getString(0);
            int numSteps = data.getInt(1);
            mHelper.getGamesClient().incrementAchievement(id, numSteps);
            callbackContext.success();
        } else if (ACTION_GAME_INCR_ACHIEVEMENT_NOW.equals(action)) {
            String id = data.getString(0);
            int numSteps = data.getInt(1);
            mHelper.getGamesClient().incrementAchievementImmediate(this, id, numSteps);
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_ACHIEVEMENTS.equals(action)) {
            boolean forceReload = data.getBoolean(0);
            mHelper.getGamesClient().loadAchievements(this, forceReload);
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_GAME.equals(action)) {
            mHelper.getGamesClient().loadGame(this);
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_LEADERBOARD_METADATA.equals(action)) {
            if (1 == data.length()) {
                mHelper.getGamesClient().loadLeaderboardMetadata(this, data.getBoolean(0));
            } else {
                mHelper.getGamesClient().loadLeaderboardMetadata(this, data.getString(0), data.getBoolean(1));
            }
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_MORE_SCORES.equals(action)) {
            if (null == scoreBuffer) {
                callbackContext.error("Get a leaderboard fist before calling: " + action);
                return false;
            }
            int maxResults = data.getInt(0);
            int pageDirection = data.getInt(0);
            mHelper.getGamesClient().loadMoreScores(this, scoreBuffer, maxResults, pageDirection);
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_PLAYER.equals(action)) {
            String playerId = data.getString(0);
            mHelper.getGamesClient().loadPlayer(this, playerId);
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_PLAYER_CENTERED_SCORES.equals(action)) {
            String leaderboardId = data.getString(0);
            int span = data.getInt(1);
            int leaderboardCollection = data.getInt(2);
            int maxResults = data.getInt(3);
            if (data.isNull(4)) {
                mHelper.getGamesClient().loadPlayerCenteredScores(this, leaderboardId, span,
                        leaderboardCollection, maxResults);
            } else {
                boolean forceReload = data.getBoolean(4);
                mHelper.getGamesClient().loadPlayerCenteredScores(this, leaderboardId, span,
                        leaderboardCollection, maxResults, forceReload);
            }
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_TOP_SCORES.equals(action)) {
            String leaderboardId = data.getString(0);
            int span = data.getInt(1);
            int leaderboardCollection = data.getInt(2);
            int maxResults = data.getInt(3);
            if (data.isNull(4)) {
                mHelper.getGamesClient().loadTopScores(this, leaderboardId, span, leaderboardCollection,
                        maxResults);
            } else {
                boolean forceReload = data.getBoolean(4);
                mHelper.getGamesClient().loadTopScores(this, leaderboardId, span, leaderboardCollection,
                        maxResults, forceReload);
            }
            callbackContext.success();
        } else if (ACTION_GAME_REVEAL_ACHIEVEMENT.equals(action)) {
            String id = data.getString(0);
            mHelper.getGamesClient().revealAchievement(id);
            callbackContext.success();
        } else if (ACTION_GAME_REVEAL_ACHIEVEMENT_NOW.equals(action)) {
            String id = data.getString(0);
            mHelper.getGamesClient().revealAchievementImmediate(this, id);
            callbackContext.success();
        } else if (ACTION_GAME_SUBMIT_SCORE.equals(action)) {
            String leaderboardId = data.getString(0);
            int score = data.getInt(1);
            mHelper.getGamesClient().submitScore(leaderboardId, score);
            callbackContext.success();
        } else if (ACTION_GAME_SUBMIT_SCORE_NOW.equals(action)) {
            String leaderboardId = data.getString(0);
            int score = data.getInt(1);
            mHelper.getGamesClient().submitScoreImmediate(this, leaderboardId, score);
            callbackContext.success();
        } else if (ACTION_GAME_UNLOCK_ACHIEVEMENT.equals(action)) {
            String id = data.getString(0);
            mHelper.getGamesClient().unlockAchievement(id);
            callbackContext.success();
        } else if (ACTION_GAME_UNLOCK_ACHIEVEMENT_NOW.equals(action)) {
            String id = data.getString(0);
            mHelper.getGamesClient().unlockAchievementImmediate(this, id);
            callbackContext.success();
        } else {
            callbackContext.error("Unknown action: " + action);
            return false;
        }
    } catch (JSONException ex) {
        callbackContext.error(ex.getMessage());
        return false;
    }

    return true;
}

From source file:com.cbtec.eliademy.FacebookConnect.java

License:Open Source License

/**
 * Cordova interface to initialize the appId
 *
 * @param args/*from   w ww .j  a  v a2 s .co m*/
 * @param callbackId
 * @return PluginResult
 * @throws JSONException
 */
public PluginResult initWithAppId(final JSONArray args, final CallbackContext callbackId) throws JSONException {
    // Log.d(CLASS, "initWithAppId()");
    JSONObject params = args.getJSONObject(0);
    PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
    JSONObject result = new JSONObject();

    this.appId = params.getString("appId");
    Facebook facebook = this.getFacebook();
    result.put("appId", this.appId);

    // Check for any stored session update Facebook session information
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(this.cordova.getActivity().getApplicationContext());
    String accessToken = prefs.getString("access_token", null);
    Long accessExpires = prefs.getLong("access_expires", 0);
    if (accessToken != null)
        facebook.setAccessToken(accessToken);
    if (accessExpires != 0)
        facebook.setAccessExpires(accessExpires);

    result.put("accessToken", accessToken);
    result.put("expirationDate", accessExpires);

    pluginResult = new PluginResult(PluginResult.Status.OK, result);
    //this.success(pluginResult, callbackId);

    return pluginResult;

}

From source file:com.cbtec.eliademy.FacebookConnect.java

License:Open Source License

/**
 * Cordova interface to perform a login//from w ww .ja va  2 s .c o  m
 *
 * @param args
 * @param callbackId
 * @return PluginResult
 * @throws JSONException
 * @throws MalformedURLException
 * @throws IOException
 */
public PluginResult login(final JSONArray args, final CallbackContext callbackId)
        throws JSONException, MalformedURLException, IOException {
    // Log.d(CLASS, "login() :" + args.toString());
    JSONObject params = args.getJSONObject(0);
    PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);

    if (params.has("appId"))
        this.appId = params.getString("appId");
    Facebook facebook = this.getFacebook();

    // Check for any stored session update Facebook session information
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(this.cordova.getActivity().getApplicationContext());
    String accessToken = prefs.getString("access_token", null);
    Long accessExpires = prefs.getLong("access_expires", 0);
    if (accessToken != null)
        facebook.setAccessToken(accessToken);
    if (accessExpires != 0)
        facebook.setAccessExpires(accessExpires);

    if (!this.getFacebook().isSessionValid()) {
        JSONArray permissionsArray = (JSONArray) params.get("permissions");
        final String[] permissions = new String[permissionsArray.length()];
        for (int i = 0; i < permissionsArray.length(); i++) {
            permissions[i] = permissionsArray.getString(i);
        }

        final FacebookConnect me = this;
        this.authorizeDialogListener = new AuthorizeDialogListener(me, callbackId);
        this.cordova.setActivityResultCallback(this);
        Runnable runnable = new Runnable() {
            public void run() {
                me.getFacebook().authorize(me.cordova.getActivity(), permissions, me.authorizeDialogListener);
            };
        };
        pluginResult.setKeepCallback(true);
        this.cordova.getActivity().runOnUiThread(runnable);
    } else {
        JSONObject result = new JSONObject(facebook.request("/me"));
        result.put("accessToken", accessToken);
        result.put("expirationDate", accessExpires);
        // Log.d(CLASS, "login::result " + result.toString());
        pluginResult = new PluginResult(PluginResult.Status.OK, result);
    }

    return pluginResult;
}

From source file:com.cbtec.eliademy.FacebookConnect.java

License:Open Source License

/**
 * Cordova interface to perfom a graph request
 *
 * @param args/*from  ww w  . j a  v a  2 s.  c om*/
 * @param callbackId
 * @return PluginResult
 * @throws JSONException
 * @throws FileNotFoundException
 * @throws MalformedURLException
 * @throws IOException
 */
public PluginResult requestWithGraphPath(final JSONArray args, final CallbackContext callbackId)
        throws JSONException, FileNotFoundException, MalformedURLException, IOException {
    // Log.d(CLASS, "requestWithGraphPath() :" + args.toString());
    JSONObject params = args.getJSONObject(0);
    PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);

    Facebook facebook = this.getFacebook();
    String path = params.has("path") ? params.getString("path") : "me";
    JSONObject optionsObject = (JSONObject) params.get("options");
    final Bundle options = new Bundle();
    Iterator<?> keys = optionsObject.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        options.putString(key, optionsObject.getString(key));
        //if(optionsObject.get(key) instanceof JSONObject)
    }
    String httpMethod = params.has("httpMethod") ? params.getString("httpMethod") : "GET";

    JSONObject result = new JSONObject(facebook.request(path, options, httpMethod));
    // Log.d(CLASS, "requestWithGraphPath::result " + result.toString());
    pluginResult = new PluginResult(PluginResult.Status.OK, result);

    return pluginResult;
}