Share to facebook from background - Android - Facebook SDK v4.x - android

I want to be able to seamlessly publish to a users Facebook feed from the background in my Android application. The user is fully aware of the content they are publishing, but the post will be made after a relatively long upload process, so the user should not be made to wait. I am using the Android Facebook SDK v4.1.2.
I see that I need to request the "publish_actions" permission from the user beforehand:
https://developers.facebook.com/docs/facebook-login/permissions/v2.3#reference-publish_actions
I can use the LoginManager to get the access token:
https://developers.facebook.com/docs/facebook-login/android/v2.3#access_profile
I am then not sure how to share a link to the users feed without using the ShareDialog:
https://developers.facebook.com/docs/sharing/android
This SO question suggests using the Request object for v3.x, which is equivalent to the GraphRequest object for v4.x:
https://developers.facebook.com/docs/reference/android/current/class/GraphRequest/
but I am not sure how to build the correct GraphRequest. I assume I need to publish a message to "/me/feed":
https://developers.facebook.com/docs/graph-api/reference/v2.3/user/feed
Can anyone tell me how to do this?

In writing the question I found my own solution from trawling the docs and examples. I need to publish a message to "/me/feed":
https://developers.facebook.com/docs/graph-api/reference/v2.3/user/feed
Bundle params = new Bundle();
params.putString("link", link);
GraphRequest request = new GraphRequest(AccessToken.getCurrentAccessToken(),
"/me/feed", params, HttpMethod.POST,
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse graphResponse) {
}
});
request.executeAndWait();
After obtaining the "publish_actions" permission.

You should use the ShareApi class if you don't want to build the params bundle yourself.
Build a ShareLinkContent as you normally would:
ShareLinkContent content = new ShareLinkContent.Builder()
.setContentUrl(Uri.parse("https://your.url.com"))
.build();
Then call ShareApi:
ShareApi.share(content, new FacebookCallback<Sharer.Result>() {...});

Related

Android Facebook Like Button

Is it possible that I place a like button on my android app clicking which likes a post which is publicly available on facebook? I do not want any additional windows to open for the task except may be for first time authentication.
All questions asked so far are related to opening a new window.
It is possible. You can perform a Like Action using Facebook's Open Graph API. In order to do so, you need to meet certain conditions:
The viewer of the in-app content is a Facebook user who has Facebook-authed and granted the app publish_actions permission
The in-app content has an Open Graph object page that is properly marked-up using Open Graph metatags
The viewer has intentionally clicked on a custom in-app “like button” associated with the in-app content
Steps at a high-level:
You need to first get the user's active Session (com.facebook.Session).
Session session = Session.getActiveSession();
Then you need to ensure that the user has the publish_actions permission. If not, request them.
List<String> requestedPermissions = Arrays.asList("publish_actions");
List<String> currentPermissions = session.getPermissions();
if (!currentPermissions.containsAll(requestedPermissions)) {
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(this, requestedPermissions);
session.requestNewPublishPermissions(newPermissionsRequest);
}
Finally, send your request to "me/og.likes". Your request should include your Session, a Bundle including the Graph object you want to like, the HTTP method, and a callback that will execute once you receive a response.
Bundle postParams = new Bundle();
postParams.putString("object", myGraphObject);
Request request = new Request(session, "me/og.likes", postParams, HttpMethod.POST, myCallback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
You want to perform these steps in your button's OnClickListener.
Hope this helps!
Resources:
Like Action
Publishing Conditions

How to create and share facebook open graph stories in android

I have created a custom object called event and I would like people to perform an action called rsvp. I would like people to be able to share this action eg "Mary has rsvped to Some Event"
I have already created the action and configured the sentences now I just need a way to programatically be able to create events. I have tried using the code:
Bundle params = new Bundle();
GraphRequest request = new GraphRequest(
AccessToken.getCurrentAccessToken(),
"me/objects/my_namespace:event",
params,
HttpMethod.POST
);
GraphResponse response = request.executeAndWait();
But I keep getting the error "(#100) The parameter object is required".
My question is What is the step-by-step way from creating open graph stories to sharing them in Android? Also, what does that error mean?

Share Score on Facebook android

I want to share my game score on facebook. I checked lots of links and every post people are saying that POSTING on facebook using INTENT is not possible.If we are using intent than we can share only link.
If we have to share something on facebook than we have to use FaceBook SDK.
I have another doubt that all questions and answers were posted before Year 2014. Is any new thing come after year 2014.
My actual question is that, Is it possible to share score on Facebook using Intent or i have to use Facebook SDK ?
below is the intent code which i used for my application which is not working ......
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, message);
startActivity(Intent.createChooser(intent, "Share on"));
and below is the FacebookSDK code ...and Problem in this it is not showing score on the Post only link image is showing, and title & description is missing.
FacebookSdk.sdkInitialize(getApplicationContext());
shareDialog = new ShareDialog(this);
if (ShareDialog.canShow(ShareLinkContent.class)) {
linkContent = new ShareLinkContent.Builder()
.setContentTitle(title)
.setContentDescription(description)
.setContentUrl(Uri.parse(link)).
.setImageUrl(Uri.parse(imageLink)
.build();
shareDialog.show(linkContent);
}
I used ShareDialog because
The Share dialog switches to the native Facebook for Android app, then returns control to your app after a post is published. If the Facebook app is not installed it will automatically fallback to the web-based dialog.
Below is the output ..........
#pravin this is error coming after your share API use
#Pravin this is my code of your share answer........
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_facebook);
Button mShare= (Button) findViewById(R.id.share);
mShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ShareOpenGraphObject object = new ShareOpenGraphObject.Builder()
.putString("og:type", "game.achievement")
.putString("og:title", "Name of your game")
.putString("og:description", "description. You can share your score here")
.putString("game:points", "445")
.build();
ShareOpenGraphAction action = new ShareOpenGraphAction.Builder()
.setActionType("games.achieves")
.putObject("game", object)
.build();
if (ShareDialog.canShow(ShareLinkContent.class)) {
ShareOpenGraphContent content = new ShareOpenGraphContent.Builder()
.setPreviewPropertyName("game")
.setAction(action)
.build();
ShareDialog.show(Facebook.this, content);
}
}
});
shareDialog = new ShareDialog(this);
}
Thanx in advance ................
After long searching i found this as work for me in my Project till the actual answer will come ..........
FacebookSdk.sdkInitialize(getApplicationContext());
shareDialog = new ShareDialog(this);
if (ShareDialog.canShow(ShareLinkContent.class)) {
linkContent = new ShareLinkContent.Builder()
.setQuote("Hi Guys I have completed Game 30 in 19 seconds in this game")
.setImageUrl(Uri.parse("https://lh3.googleusercontent.com/jUej7mN6M6iulmuwmW6Mk28PrzXgl-Ebn-MpTmkmwtOfj5f0hvnuw8j0NEzK0GuKoDE=w300-rw"))
.setContentUrl(Uri.parse("https://play.google.com/store/apps/details?id=com.mobtraffiq.numbertap&hl=en"))
.build();
shareDialog.show(linkContent);
}
NOTE:-In this code its shared a quota. If any one get other answer please post with output.
Output:-
Please post guys if you get the actual answer of this question ....
Thank you for all the user who make their effort .......
I have learn many thing due to your answers .......
enjoy coding .........
Scores API
If you just want to share score you can use Scores API(Read Create or Update a Player's Score section). There is very less and unclear information in provided link so below code snippet might work for you.
Bundle param = new Bundle();
param.putInt("score", 100);
new GraphRequest(
your_access_token,
"/USER_ID/scores",
param,
HttpMethod.POST,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
}
}
).executeAsync();
Achievements API
Use Achievements API if you want to publish achievements in your game and reward players with scores for completing those achievements.You have to use Open Graph Stories to publish your game achievements on Facebook. Before publishing stories on behalf of people, You will have to submit them for review. Read this link for more information.There are two ways to publish an Open Graph story:
Using the Share dialog
Using your own custom interface
As you are using share dialog, I am going to throw some light on how to post game score using share dialog.
Create an object with the object type game.achievement and set the properties on that object.
ShareOpenGraphObject object = new ShareOpenGraphObject.Builder()
.putString("og:type", "game.achievement")
.putString("title", "Title of the achievement type.")
.putString("og:description", "description. You can share your score here")
.putInt("game:points", Points in integer)
.putString("og:url", "url of achievement type")
.putString("og:image", "image url")
.putString("fb:app_id", "The App ID that owns this achievement type")
.build();
In above code snippet key is Object Properties and game.achievement is Object Type. Here is documentation for game:points.
Then create an action and link the object to the action.
ShareOpenGraphAction action = new ShareOpenGraphAction.Builder()
.setActionType("games.achieves")
.putObject("game", object)
.build();
You can find different ActionTypes here.
Finally, create the content model to represent the Open Graph story.
ShareOpenGraphContent content = new ShareOpenGraphContent.Builder()
.setPreviewPropertyName("game")
.setAction(action)
.build();
All objects and action types in your code must be lowercase. All
property names require namespaces.
Present the Share dialog by using the show method on ShareDialog.
ShareDialog.show(activityOrFragment, content);
Summary:-
The Scores API and Achievements API make it easy to build social
leaderboards, persist player scores and award achievements to players
in a social and cross-platform format. With the Scores API, you can
store and reset a player's high-score and pull back a list of their
friends' scores to populate a leaderboard. With the Achievements API,
you can define a list of custom achievements that players can complete
in your game, along with a score value that can be earned with each
achievement.
Note:-
Both the Scores API and Achievements API are only available for apps
that are categorized as Games.
Because these API let developers write information about player game
state to the Graph API, they both require publish_actions permissions,
which is subject to Login Review. To retrieve Score and Achievement
information about a player's friends, both the player and their
friends need to grant the user_friends permission.
Hope this will provide you and other users enough information on game integration with Facebook.
Just try the below snippet,
call wherever you want like below
ShareDialog shareDialog;
FacebookSdk.sdkInitialize(mContext);
shareDialog = new ShareDialog(mContext);
shareScoreonFB("345"); // just pass your score here in string format. call this inside click listener.
// GLOBAL FUNCTION TO SHARE SCORE ON FB
void shareScoreonFB(String score)
{
ShareLinkContent linkContent = new ShareLinkContent.Builder()
.setContentTitle("Your score is : "+score)
.setContentDescription("Any description that you needed")
.setContentUrl(Uri.parse("https://play.google.com/store/apps/details?id=com.mobtraffiq.numbertap&hl=en")).build();
shareDialog.show(linkContent);
}
NOTE: Make sure you initialize the Facebook SDK.
Hope this helps you, let me know for queries.
I believe that the Facebook SDK uses a background Activity for the actual data transfer, but you still need to make your own activity, its layout, and the examples on here show you how to create your own Sharing and Login tools
You have to use Facebook SDK to do this, I think the main reason is about security.
This is a simple snippet for photo sharing example (not related to your question but i think you know you can't not do it by using Intent):
private void shareImage() {
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(bmp)
.setCaption("Simple puzzle")
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
ShareApi.share(content, null);
}
Well, there are 3 things you should do :
1) Categorize your app as Games on Facebook Developers
2) Use the Achievements API and Scores API
3) Facebook for Developers officially has an answer to your question. Please refer to the link https://developers.facebook.com/docs/games/services/scores-achievements
[ OPTIONAL ]
If you want to study about General Sharing from your app by users than this link Facebook SharingAddit might also help you in as General Sharing of content from your app

Facebook like button implementation in android

I know this question has been asked so many times.
In my app I also want to integrate Facebook like button,after doing lots of R&D I came across the below link
https://developers.facebook.com/docs/reference/opengraph/action-type/og.likes
and I am using the below code in my app,
Bundle params = new Bundle();
params.putString("object", "http://samples.ogp.me/226075010839791");
Request request = new Request(
Session.getActiveSession(),
"me/og.likes",
params,
HttpMethod.POST
);
Response response = request.executeAndWait();
// handle the response
but when I click the like button nothing is happening.
Could you all please guide me how to use the above code.
One more thing an extra permission is needed for implementing the above code "Permission: publish_actions".How to get this permission?
First open session with publish permission using this

Post photo to Facebook parameters

I am posting a photo to FB using the new FB Android SDK 3.0. I am now looking for a way to set some more parameters than just the image itself and a simple text. I tried tons of different parameters, but non of them seem to do something.
What i would like to do is to add a link, an icon and, if somehow possible, a custom link item next to the Like and Comment links.
Here is an example of the icon and the custom link item from twitter:
And this is the code that I am currently using:
byte[] data = get binary image data;
Bundle postParams = new Bundle();
postParams.putString("name", "Image text");
postParams.putByteArray("picture", data);
// All these parameters do nothing...
postParams.putString("icon", "http://www.myimage.com/image.png");
postParams.putString("message", "XXX");
postParams.putString("caption", "Build great social apps and get more installs.");
postParams.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
postParams.putString("link", "https://developers.facebook.com/android");
Request request = new Request(Session.getActiveSession(), "me/photos", postParams, HttpMethod.POST);
Response r = request.executeAndWait();
The post looks like this:
1. Adding the icon
You can manage icons from your app's dashboard: https://developers.facebook.com/apps/APP_ID/appdetails
2. Adding an action link
What you can a "custom link" is in fact an "action".
The "action" you've seen on the Twitter's post has been done using the actions array from the Post table:
A list of available actions on the post (including commenting, liking,
and an optional app-specified action)
So, your only choice if you really want to add this action near Like · Comment is to create a Post into the Feed and not a Photo.
Here is an a priori working code:
postParams.putString("message", "XXX");
postParams.putString("caption", "developers.facebook.com");
postParams.putString("description", "A tool to help you learn and browse the Facebook Graph API.");
postParams.putString("actions", "[{
'name':'Test a simple Graph API call!',
'link':'https://developers.facebook.com/tools/explorer?method=GET&path=me'
/* ^ This link must direct to the application's connect or canvas URL.
You'll get an error otherwise. */
}]"
);
postParams.putString("type", "photo");
postParams.putString("link", "https://developers.facebook.com/tools/explorer/");
postParams.putString("picture", "http://blog.programmableweb.com/wp-content/ishot-44.png");
Request request = new Request(Session.getActiveSession(), "me/feed", postParams, HttpMethod.POST);
3. Test in the Graph API Explorer
4. Timeline preview

Categories

Resources