1、打开 res/layout/activity_main.xml,在布局中添加一个facebook分享按钮
<Button
android:id="@+id/shareButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center"
android:text="@string/share"
android:textStyle="bold"
android:visibility="invisible" />
其中,android:visibility="invisible" 在登陆之前是隐藏的,在登陆之后才设置显示。
2、在MainFragment中的onSessionStateChange()这个函方法中添加修改,使用户登陆之后就把分享按钮设置成visible。
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
shareButton.setVisibility(View.VISIBLE);
if (pendingPublishReauthorization &&
state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
pendingPublishReauthorization = false;
publishStory();
}
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
shareButton.setVisibility(View.INVISIBLE);
}
}
2、在MainFragment中添加一个方法publishStory(),在此部分添加修改链接、图片和分享内容
private void publishStory() {
Session session = Session.getActiveSession();
if (session != null){
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return; } Bundle postParams = new Bundle();
postParams.putString("name", "Facebook SDK for Android");
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");
postParams.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
Request.Callback callback= new Request.Callback() {
public void onCompleted(Response response) {
JSONObject graphResponse = response
.getGraphObject()
.getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (JSONException e) {
Log.i(TAG,
"JSON error "+ e.getMessage());
} FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(getActivity()
.getApplicationContext(),
error.getErrorMessage(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity()
.getApplicationContext(),
postId,
Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(session, "me/feed", postParams,
HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}}
}
}
4、再添加isSubsetOf()方法:
private boolean isSubsetOf(Collection<String> subset,
Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
5、在MainFragment的声明部分加上:
rivate Button shareButton;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
6、在onSaveInstanceState()方法里再添加一句,如下:
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
uiHelper.onSaveInstanceState(outState);
}
7、在onActivityResult()方法里面注释
//uiHelper.onActivityResult(requestCode, resultCode, data);
并加上
uiHelper.onActivityResult(requestCode, resultCode, data, new FacebookDialog.Callback() {
@Override
public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
Log.e("Activity", String.format("Error: %s", error.toString()));
}
@Override
public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
Log.i("Activity", "Success!");
}
});
如图:
8、在onCreateView()方法里添加shareButton的click事件即可
shareButton = (Button) view.findViewById(R.id.shareButton);
shareButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
publishStory();
}
});
if (savedInstanceState != null) {
pendingPublishReauthorization =
savedInstanceState.getBoolean(PENDING_PUBLISH_KEY, false);
}
如下图:
9、分享结果如下,当然,这是后台分享:
10、前台分享,在shareButton的onclick事件中,把publishStory()替换为publishFeedDialog(),并添加publishFeedDialog()方法,就可以了:
@Override
public void onClick(View v) {
// publishStory(); //后台分享
publishFeedDialog(); //前台分享
if (FacebookDialog.canPresentShareDialog(getActivity()
.getApplicationContext(),
FacebookDialog.ShareDialogFeature.SHARE_DIALOG)) {
// Publish the post using the Share Dialog
FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(
getActivity()).setLink(
"https://developers.facebook.com/android").build();
uiHelper.trackPendingDialogCall(shareDialog.present());
} else {
// Fallback. For example, publish the post using the Feed
// Dialog
}
}
添加publishFeedDialog()方法:
private void publishFeedDialog() {
Bundle params = new Bundle();
params.putString("name", "Facebook SDK for Android");
params.putString("caption",
"Build great social apps and get more installs.");
params.putString(
"description",
"The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
params.putString("link", "https://developers.facebook.com/android");
params.putString("picture",
"https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(getActivity(),
Session.getActiveSession(), params)).setOnCompleteListener(
new OnCompleteListener() {
@Override
public void onComplete(Bundle values,
FacebookException error) {
if (error == null) {
// When the story is posted, echo the success
// and the post Id.
final String postId = values.getString("post_id");
if (postId != null) {
Toast.makeText(getActivity(),
"Posted story, id: " + postId,
Toast.LENGTH_SHORT).show();
} else {
// User clicked the Cancel button
Toast.makeText(
getActivity().getApplicationContext(),
"Publish cancelled", Toast.LENGTH_SHORT)
.show();
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
Toast.makeText(
getActivity().getApplicationContext(),
"Publish cancelled", Toast.LENGTH_SHORT)
.show();
} else {
// Generic, ex: network error
Toast.makeText(
getActivity().getApplicationContext(),
"Error posting story", Toast.LENGTH_SHORT)
.show();
}
}
}).build();
feedDialog.show();
}
如下图:注释掉后台分享部分,添加前台分享代码:
11、附上MainFragment的代码
package com.example.kam;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.FacebookRequestError;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.FacebookDialog;
import com.facebook.widget.LoginButton;
import com.facebook.widget.WebDialog;
import com.facebook.widget.WebDialog.OnCompleteListener;
public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
private UiLifecycleHelper uiHelper;
private Button shareButton;
private static final List<String> PERMISSIONS = Arrays
.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
private Session.StatusCallback callback = new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
shareButton = (Button) view.findViewById(R.id.shareButton);
shareButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// publishStory(); //后台分享
publishFeedDialog(); //前台分享
if (FacebookDialog.canPresentShareDialog(getActivity()
.getApplicationContext(),
FacebookDialog.ShareDialogFeature.SHARE_DIALOG)) {
// Publish the post using the Share Dialog
FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(
getActivity()).setLink(
"https://developers.facebook.com/android").build();
uiHelper.trackPendingDialogCall(shareDialog.present());
} else {
// Fallback. For example, publish the post using the Feed
// Dialog
}
}
});
LoginButton authButton = (LoginButton) view
.findViewById(R.id.login_button);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("email", "user_likes",
"user_status"));
if (savedInstanceState != null) {
pendingPublishReauthorization = savedInstanceState.getBoolean(
PENDING_PUBLISH_KEY, false);
}
return view;
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
shareButton.setVisibility(View.VISIBLE);
if (pendingPublishReauthorization
&& state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
pendingPublishReauthorization = false;
// publishStory();
publishFeedDialog();
}
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
shareButton.setVisibility(View.INVISIBLE);
}
}
@Override
public void onResume() {
super.onResume();
// For scenarios where the main activity is launched and user
// session is not null, the session state change notification
// may not be triggered. Trigger it if it's open/closed.
Session session = Session.getActiveSession();
if (session != null && (session.isOpened() || session.isClosed())) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// uiHelper.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data,
new FacebookDialog.Callback() {
@Override
public void onError(FacebookDialog.PendingCall pendingCall,
Exception error, Bundle data) {
Log.e("Activity",
String.format("Error: %s", error.toString()));
}
@Override
public void onComplete(
FacebookDialog.PendingCall pendingCall, Bundle data) {
Log.i("Activity", "Success!");
}
});
}
@Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
uiHelper.onSaveInstanceState(outState);
}
private void publishStory() {
Session session = Session.getActiveSession();
if (session != null) {
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(
this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
Bundle postParams = new Bundle();
postParams.putString("name", "Facebook SDK for Android");
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");
postParams
.putString("picture",
"https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
Request.Callback callback = new Request.Callback() {
public void onCompleted(Response response) {
JSONObject graphResponse = response.getGraphObject()
.getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (JSONException e) {
Log.i(TAG, "JSON error " + e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(getActivity().getApplicationContext(),
error.getErrorMessage(), Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(getActivity().getApplicationContext(),
postId, Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(session, "me/feed", postParams,
HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
private boolean isSubsetOf(Collection<String> subset,
Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
private void publishFeedDialog() {
Bundle params = new Bundle();
params.putString("name", "Facebook SDK for Android");
params.putString("caption",
"Build great social apps and get more installs.");
params.putString(
"description",
"The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
params.putString("link", "https://developers.facebook.com/android");
params.putString("picture",
"https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(getActivity(),
Session.getActiveSession(), params)).setOnCompleteListener(
new OnCompleteListener() {
@Override
public void onComplete(Bundle values,
FacebookException error) {
if (error == null) {
// When the story is posted, echo the success
// and the post Id.
final String postId = values.getString("post_id");
if (postId != null) {
Toast.makeText(getActivity(),
"Posted story, id: " + postId,
Toast.LENGTH_SHORT).show();
} else {
// User clicked the Cancel button
Toast.makeText(
getActivity().getApplicationContext(),
"Publish cancelled", Toast.LENGTH_SHORT)
.show();
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
Toast.makeText(
getActivity().getApplicationContext(),
"Publish cancelled", Toast.LENGTH_SHORT)
.show();
} else {
// Generic, ex: network error
Toast.makeText(
getActivity().getApplicationContext(),
"Error posting story", Toast.LENGTH_SHORT)
.show();
}
}
}).build();
feedDialog.show();
}
}