【FacebookSDK学习笔记】Facebook分享(在登陆的基础上)

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();
	}
}

时间: 2024-10-10 17:12:36

【FacebookSDK学习笔记】Facebook分享(在登陆的基础上)的相关文章

jQuery学习笔记--JqGrid相关操作 方法列表(上)

1.获得当前列表行数:$("#gridid").getGridParam("reccount"); 2.获取选中行数据(json):$("#gridid").jqGrid('getRowData', id); 3.刷新列表:$(refreshSelector).jqGrid('setGridParam', { url: ''), postData: ''}).trigger('reloadGrid'); 4.选中行:$("#jqGrid

计算机操作系统学习笔记_2_进程管理 --进程与线程(上)

h3.western { font-family: "Liberation Sans",sans-serif; }h3.cjk { font-family: "微软雅黑"; }h3.ctl { font-family: "AR PL UMing CN"; }h2.western { font-family: "Liberation Sans",sans-serif; font-size: 16pt; }h2.cjk { fon

Linux 程序设计学习笔记----进程管理与程序开发(上)

转载请注明出处,http://blog.csdn.net/suool/article/details/38406211,谢谢! Linux进程存储结构和进程结构 可执行文件结构 如下图: 可以看出,此ELF可执行文件存储时(没有调入内存)分为代码区.数据区和未出花数据区三部分. 代码区:存放cpu的执行的机器指令. 数据区:包含程序中的已经初始化的静态变量,以及已经初始化的全局变量. 未初始化数据区:存入的是未初始化的全局变量和未初始化的静态变量. 现在在上面的程序代码中增加一个int的静态变量

【慕课网】php工程师学习计划之我的学习笔记——01 入门必学web基础 htmlcss基础课程 篇

为了进一步学习PHP,本周我选定了慕课网的PHP工程师学习计划, 从今天2015-07-06 10:24:47开始从头学习:计划本周尽快学习完成本课程,谨此作为笔记. 有个好的学习计划和思路非常非常重要,非常感谢慕课网提供本套学习计划,希望更多地学习平台能提供像这样全面一条龙学习思路清晰地教程. 计划图:链接 我的学习状况:2015-07-06 10:29:46 开始随记: php工程师学习计划笔记——01 入门必学web基础 htmlcss基础课程 篇 入门篇: text-align:cent

数字图像处理学习笔记之一 DIP绪论与MATLAB基础

写在前面的话 数字图像处理系列的学习笔记是作者结合上海大学计算机学院<数字图像处理>课程的学习所做的笔记,使用参考书籍为<冈萨雷斯数字图像处理(第二版)(MATLAB版)>,同时学习过程中会参考网络学习资源.对于数字图像处理的学习不可能仅仅依靠作者所写的这一系列笔记,而是需要花时间和精力学习,本文只可作参考和交流之用.由于涉及此学科不久,在学习过程中难免存在错误,请读者不吝赐教. 数字图像处理绪论 数字图像处理(DIP)的研究目标和处理对象: DIP的研究目标是获取信息,处理对象是

Asp.Net Identity学习笔记+MVC5默认项目解析_基础用法

前言ASP.NET Identity特性Identity包基本IdentityUserUserManager准备工作ApplicationDbContextApplicationUserManager注册案例登入案例用户信息验证用户名密码验证器自定义验证器 前言 本文简单介绍Identity的使用,使用的案例是基于默认的Mvc5项目(只勾选MVC,不勾选WebApi).读者可以拿着项目源码对照地看. ASP.NET Identity特性 One ASP.NET Identity 系统 更容易加入

学习笔记 第十五章 JavaScript基础

第15章   JavaScript基础 [学习重点] 了解JavaScript基础知识 熟悉常量和变量 能够使用表达式和运算符 正确使用语句 能够掌握数据类型和转换的基本方法 正确使用函数.对象.数组等核心知识和技法 能够编写简单的脚本,解决网页中常见特效和互动效果 15.1  JavaScript入门 JavaScript是一种轻量级.解释型的Web开发语言.现代浏览器都已嵌入了JavaScript引擎./sc 15.1.1 在网页中插入JavaScript代码 使用<script>标签,可

【FacebookSDK学习笔记】Facebook消息分享

1.手机上要安装了Facebook Message才能使用这个功能 Google Play网址:https://play.google.com/store/apps/details?id=com.facebook.orca 2.直接添加一个button <Button android:id="@+id/messageButton" android:layout_width="match_parent" android:layout_height="w

【FacebookSDK学习笔记】Facebook官方Demo例子简单分析

1· FriendPickerSample -选择好友,但是这个demo的好友列表是空白的,要在Scrumptious 这个demo例子中的Pick Friends才可以看到完整的效果. 2· PlacePickerSample - 可以选择登陆的地点 选择地点后分享成果: 3.SwitchUserSample -可以变更账户的例子,即多账户切换. 4.AdUnitsSample and NativeAdSample-在你的app中嵌入广告.官方的demo直接运行是不能加载广告的,因为"Plac