Search in sources :

Example 21 with GraphRequest

use of com.facebook.GraphRequest in project facebook-android-sdk by facebook.

the class AppEventsLogger method updateUserProperties.

public static void updateUserProperties(final Bundle parameters, final String applicationID, final GraphRequest.Callback callback) {
    final String userID = getUserID();
    if (userID == null || userID.isEmpty()) {
        Logger.log(LoggingBehavior.APP_EVENTS, TAG, "AppEventsLogger userID cannot be null or empty");
        return;
    }
    getAnalyticsExecutor().execute(new Runnable() {

        @Override
        public void run() {
            Bundle userPropertiesParams = new Bundle();
            userPropertiesParams.putString("user_unique_id", userID);
            userPropertiesParams.putBundle("custom_data", parameters);
            // This call must be run on the background thread
            AttributionIdentifiers identifiers = AttributionIdentifiers.getAttributionIdentifiers(FacebookSdk.getApplicationContext());
            if (identifiers != null && identifiers.getAndroidAdvertiserId() != null) {
                userPropertiesParams.putString("advertiser_id", identifiers.getAndroidAdvertiserId());
            }
            Bundle data = new Bundle();
            try {
                JSONObject userData = BundleJSONConverter.convertToJSON(userPropertiesParams);
                JSONArray dataArray = new JSONArray();
                dataArray.put(userData);
                data.putString("data", dataArray.toString());
            } catch (JSONException ex) {
                throw new FacebookException("Failed to construct request", ex);
            }
            GraphRequest request = new GraphRequest(AccessToken.getCurrentAccessToken(), String.format(Locale.US, "%s/user_properties", applicationID), data, HttpMethod.POST, callback);
            request.setSkipClientToken(true);
            request.executeAsync();
        }
    });
}
Also used : GraphRequest(com.facebook.GraphRequest) JSONObject(org.json.JSONObject) AttributionIdentifiers(com.facebook.internal.AttributionIdentifiers) Bundle(android.os.Bundle) FacebookException(com.facebook.FacebookException) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException)

Example 22 with GraphRequest

use of com.facebook.GraphRequest in project facebook-android-sdk by facebook.

the class FacebookAppLinkResolver method getAppLinkFromUrlsInBackground.

/**
     * Asynchronously resolves App Link data for multiple URLs
     *
     * @param uris A list of Uri objects to resolve into App Links
     * @return A Task that, when successful, will return a Map of Uri->AppLink for each Uri that was
     * successfully resolved into an App Link. Uris that could not be resolved into App Links will
     * not be present in the Map. In the case of general server errors, the task will be completed
     * with the corresponding error.
     */
public Task<Map<Uri, AppLink>> getAppLinkFromUrlsInBackground(List<Uri> uris) {
    final Map<Uri, AppLink> appLinkResults = new HashMap<Uri, AppLink>();
    final HashSet<Uri> urisToRequest = new HashSet<Uri>();
    StringBuilder graphRequestFields = new StringBuilder();
    for (Uri uri : uris) {
        AppLink appLink;
        synchronized (cachedAppLinks) {
            appLink = cachedAppLinks.get(uri);
        }
        if (appLink != null) {
            appLinkResults.put(uri, appLink);
        } else {
            if (!urisToRequest.isEmpty()) {
                graphRequestFields.append(',');
            }
            graphRequestFields.append(uri.toString());
            urisToRequest.add(uri);
        }
    }
    if (urisToRequest.isEmpty()) {
        return Task.forResult(appLinkResults);
    }
    final Task<Map<Uri, AppLink>>.TaskCompletionSource<Map<Uri, AppLink>> taskCompletionSource = Task.create();
    Bundle appLinkRequestParameters = new Bundle();
    appLinkRequestParameters.putString("ids", graphRequestFields.toString());
    appLinkRequestParameters.putString("fields", String.format("%s.fields(%s,%s)", APP_LINK_KEY, APP_LINK_ANDROID_TARGET_KEY, APP_LINK_WEB_TARGET_KEY));
    GraphRequest appLinkRequest = new GraphRequest(// token
    AccessToken.getCurrentAccessToken(), /* Access Token */
    "", /* Graph path */
    appLinkRequestParameters, /* Query parameters */
    null, /* HttpMethod */
    new GraphRequest.Callback() {

        /* Callback */
        @Override
        public void onCompleted(GraphResponse response) {
            FacebookRequestError error = response.getError();
            if (error != null) {
                taskCompletionSource.setError(error.getException());
                return;
            }
            JSONObject responseJson = response.getJSONObject();
            if (responseJson == null) {
                taskCompletionSource.setResult(appLinkResults);
                return;
            }
            for (Uri uri : urisToRequest) {
                String uriString = uri.toString();
                if (!responseJson.has(uriString)) {
                    continue;
                }
                JSONObject urlData;
                try {
                    urlData = responseJson.getJSONObject(uri.toString());
                    JSONObject appLinkData = urlData.getJSONObject(APP_LINK_KEY);
                    JSONArray rawTargets = appLinkData.getJSONArray(APP_LINK_ANDROID_TARGET_KEY);
                    int targetsCount = rawTargets.length();
                    List<AppLink.Target> targets = new ArrayList<AppLink.Target>(targetsCount);
                    for (int i = 0; i < targetsCount; i++) {
                        AppLink.Target target = getAndroidTargetFromJson(rawTargets.getJSONObject(i));
                        if (target != null) {
                            targets.add(target);
                        }
                    }
                    Uri webFallbackUrl = getWebFallbackUriFromJson(uri, appLinkData);
                    AppLink appLink = new AppLink(uri, targets, webFallbackUrl);
                    appLinkResults.put(uri, appLink);
                    synchronized (cachedAppLinks) {
                        cachedAppLinks.put(uri, appLink);
                    }
                } catch (JSONException e) {
                    // The data for this uri was missing or badly formed.
                    continue;
                }
            }
            taskCompletionSource.setResult(appLinkResults);
        }
    });
    appLinkRequest.executeAsync();
    return taskCompletionSource.getTask();
}
Also used : Task(bolts.Task) GraphRequest(com.facebook.GraphRequest) HashMap(java.util.HashMap) Bundle(android.os.Bundle) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) Uri(android.net.Uri) FacebookRequestError(com.facebook.FacebookRequestError) JSONObject(org.json.JSONObject) GraphResponse(com.facebook.GraphResponse) AppLink(bolts.AppLink) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 23 with GraphRequest

use of com.facebook.GraphRequest in project facebook-android-sdk by facebook.

the class Utility method getGraphMeRequestWithCache.

private static GraphRequest getGraphMeRequestWithCache(final String accessToken) {
    Bundle parameters = new Bundle();
    parameters.putString("fields", "id,name,first_name,middle_name,last_name,link");
    parameters.putString("access_token", accessToken);
    GraphRequest graphRequest = new GraphRequest(null, "me", parameters, HttpMethod.GET, null);
    return graphRequest;
}
Also used : GraphRequest(com.facebook.GraphRequest) Bundle(android.os.Bundle)

Example 24 with GraphRequest

use of com.facebook.GraphRequest in project facebook-android-sdk by facebook.

the class Utility method getGraphMeRequestWithCacheAsync.

public static void getGraphMeRequestWithCacheAsync(final String accessToken, final GraphMeRequestWithCacheCallback callback) {
    JSONObject cachedValue = ProfileInformationCache.getProfileInformation(accessToken);
    if (cachedValue != null) {
        callback.onSuccess(cachedValue);
        return;
    }
    GraphRequest.Callback graphCallback = new GraphRequest.Callback() {

        @Override
        public void onCompleted(GraphResponse response) {
            if (response.getError() != null) {
                callback.onFailure(response.getError().getException());
            } else {
                ProfileInformationCache.putProfileInformation(accessToken, response.getJSONObject());
                callback.onSuccess(response.getJSONObject());
            }
        }
    };
    GraphRequest graphRequest = getGraphMeRequestWithCache(accessToken);
    graphRequest.setCallback(graphCallback);
    graphRequest.executeAsync();
}
Also used : GraphRequest(com.facebook.GraphRequest) JSONObject(org.json.JSONObject) GraphResponse(com.facebook.GraphResponse)

Example 25 with GraphRequest

use of com.facebook.GraphRequest in project facebook-android-sdk by facebook.

the class AppEventQueue method sendEventsToServer.

private static FlushStatistics sendEventsToServer(FlushReason reason, AppEventCollection appEventCollection) {
    FlushStatistics flushResults = new FlushStatistics();
    Context context = FacebookSdk.getApplicationContext();
    boolean limitEventUsage = FacebookSdk.getLimitEventAndDataUsage(context);
    List<GraphRequest> requestsToExecute = new ArrayList<>();
    for (AccessTokenAppIdPair accessTokenAppId : appEventCollection.keySet()) {
        GraphRequest request = buildRequestForSession(accessTokenAppId, appEventCollection.get(accessTokenAppId), limitEventUsage, flushResults);
        if (request != null) {
            requestsToExecute.add(request);
        }
    }
    if (requestsToExecute.size() > 0) {
        Logger.log(LoggingBehavior.APP_EVENTS, TAG, "Flushing %d events due to %s.", flushResults.numEvents, reason.toString());
        for (GraphRequest request : requestsToExecute) {
            // Execute the request synchronously. Callbacks will take care of handling errors
            // and updating our final overall result.
            request.executeAndWait();
        }
        return flushResults;
    }
    return null;
}
Also used : Context(android.content.Context) GraphRequest(com.facebook.GraphRequest) ArrayList(java.util.ArrayList)

Aggregations

GraphRequest (com.facebook.GraphRequest)29 Bundle (android.os.Bundle)22 GraphResponse (com.facebook.GraphResponse)17 JSONObject (org.json.JSONObject)16 JSONException (org.json.JSONException)12 FacebookException (com.facebook.FacebookException)9 AccessToken (com.facebook.AccessToken)5 FacebookCallback (com.facebook.FacebookCallback)5 FacebookRequestError (com.facebook.FacebookRequestError)5 Uri (android.net.Uri)3 CollectionMapper (com.facebook.internal.CollectionMapper)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 ArrayList (java.util.ArrayList)2 JSONArray (org.json.JSONArray)2 Context (android.content.Context)1 Intent (android.content.Intent)1 Bitmap (android.graphics.Bitmap)1 ParcelFileDescriptor (android.os.ParcelFileDescriptor)1 View (android.view.View)1 Button (android.widget.Button)1