私のアプリのユーザーが、私のアプリケーション内の実績などのために、私のアプリケーションからウォールにストーリーを公開できるようにしようとしています。HelloFacebookActivitySample を基にしたアクティビティ コードを次に示します。
どちらのアクティビティでも、投稿時にアプリ名、説明、リンクを問題なく確認できます。FB SDK の最新バージョンを使用します。しかし、newStatusUpdateRequest() メソッドで渡した文字列 (メッセージ) が表示されません。
(この試みでは、テキストビューからテキストを渡そうとしています)最初に試した方法:
public class Settings_Facebook extends FragmentActivity {
//Constants
private static final String PERMISSION = "publish_actions";
private final String PENDING_ACTION_BUNDLE_KEY = "com.facebook.MyApp:PendingAction";
//Views
private Button postStatusUpdateButton;
private Button postPhotoButton;
private LoginButton loginButton;
private ProfilePictureView profilePictureView;
private TextView greeting;
//Variables
private PendingAction pendingAction = PendingAction.NONE;
private ViewGroup controlsContainer;
private GraphUser user;
private GraphPlace place;
private List<GraphUser> tags;
private boolean canPresentShareDialog;
private enum PendingAction {
NONE,
POST_PHOTO,
POST_STATUS_UPDATE
}
private UiLifecycleHelper uiHelper;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
if (savedInstanceState != null) {
String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
pendingAction = PendingAction.valueOf(name);
}
setContentView(R.layout.activity_settings__facebook);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
@Override
public void onUserInfoFetched(GraphUser user) {
Settings_Facebook.this.user = user;
updateUI();
// It's possible that we were waiting for this.user to be populated in order to post a
// status update.
handlePendingAction();
}
});
profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
greeting = (TextView) findViewById(R.id.greeting);
postStatusUpdateButton = (Button) findViewById(R.id.postStatusUpdateButton);
postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPostStatusUpdate();
}
});
postPhotoButton = (Button) findViewById(R.id.postPhotoButton);
postPhotoButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPostPhoto();
}
});
controlsContainer = (ViewGroup) findViewById(R.id.main_ui_container);
canPresentShareDialog = FacebookDialog.canPresentShareDialog(this,
FacebookDialog.ShareDialogFeature.SHARE_DIALOG);
}
private Session.StatusCallback callback = new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
@Override
public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
Log.d("HelloFacebook", String.format("Error: %s", error.toString()));
}
@Override
public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
Log.d("HelloFacebook", "Success!");
}
};
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (pendingAction != PendingAction.NONE &&
(exception instanceof FacebookOperationCanceledException ||
exception instanceof FacebookAuthorizationException)) {
new AlertDialog.Builder(Settings_Facebook.this)
.setTitle(R.string.cancelled)
.setMessage(R.string.permission_not_granted)
.setPositiveButton(R.string.ok, null)
.show();
pendingAction = PendingAction.NONE;
} else if (state == SessionState.OPENED_TOKEN_UPDATED) {
handlePendingAction();
}
updateUI();
}
private void updateUI() {
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session.isOpened());
postStatusUpdateButton.setEnabled(enableButtons || canPresentShareDialog);
postPhotoButton.setEnabled(enableButtons);
if (enableButtons && user != null) {
profilePictureView.setProfileId(user.getId());
greeting.setText(getString(R.string.hello_user, user.getFirstName()));
} else {
profilePictureView.setProfileId(null);
greeting.setText(null);
}
}
@SuppressWarnings("incomplete-switch")
private void handlePendingAction() {
PendingAction previouslyPendingAction = pendingAction;
// These actions may re-set pendingAction if they are still pending, but we assume they
// will succeed.
pendingAction = PendingAction.NONE;
switch (previouslyPendingAction) {
case POST_PHOTO:
postPhoto();
break;
case POST_STATUS_UPDATE:
postStatusUpdate();
break;
}
}
private interface GraphObjectWithId extends GraphObject {
String getId();
}
private void showPublishResult(String message, GraphObject result, FacebookRequestError error) {
String title = null;
String alertMessage = null;
if (error == null) {
title = getString(R.string.success);
String id = result.cast(GraphObjectWithId.class).getId();
alertMessage = getString(R.string.successfully_posted_post, message, id);
} else {
title = getString(R.string.error);
alertMessage = error.getErrorMessage();
}
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(alertMessage)
.setPositiveButton(R.string.ok, null)
.show();
}
private void onClickPostStatusUpdate() {
performPublish(PendingAction.POST_STATUS_UPDATE, canPresentShareDialog);
}
private FacebookDialog.ShareDialogBuilder createShareDialogBuilder() {
return new FacebookDialog.ShareDialogBuilder(this)
.setName("MyApplication")
.setDescription("The description of the app")
.setLink("https://play.google.com/store/");
}
private void postStatusUpdate() {
final EditText simpleEditText = (EditText) findViewById(R.id.editStatus);
final String message = simpleEditText.getText().toString();
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");
if (canPresentShareDialog) {
FacebookDialog shareDialog = createShareDialogBuilder().build();
uiHelper.trackPendingDialogCall(shareDialog.present());
}
else if (user != null && hasPublishPermission()) {
Session session = Session.getActiveSession();
Request request = new Request(session,"me/feed",postParams,HttpMethod.POST);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
// .newStatusUpdateRequest(Session.getActiveSession(), message, place, tags, new Request.Callback() {
// @Override
// public void onCompleted(Response response) {
// showPublishResult(message, response.getGraphObject(), response.getError());
// }
// });
// request.executeAsync();
}
else {
pendingAction = PendingAction.POST_STATUS_UPDATE;
}
}
private void onClickPostPhoto() {
performPublish(PendingAction.POST_PHOTO, false);
}
private void postPhoto() {
if (hasPublishPermission()) {
Bitmap image = BitmapFactory.decodeResource(this.getResources(), R.drawable.button_focus);
Request request = Request.newUploadPhotoRequest(Session.getActiveSession(), image, new Request.Callback() {
@Override
public void onCompleted(Response response) {
showPublishResult(getString(R.string.photo_post), response.getGraphObject(), response.getError());
}
});
request.executeAsync();
} else {
pendingAction = PendingAction.POST_PHOTO;
}
}
private boolean hasPublishPermission() {
Session session = Session.getActiveSession();
return session != null && session.getPermissions().contains("publish_actions");
}
private void performPublish(PendingAction action, boolean allowNoSession) {
Session session = Session.getActiveSession();
if (session != null) {
pendingAction = action;
if (hasPublishPermission()) {
// We can do the action right away.
handlePendingAction();
return;
} else if (session.isOpened()) {
// We need to get new permissions, then complete the action when we get called back.
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, PERMISSION));
return;
}
}
if (allowNoSession) {
pendingAction = action;
handlePendingAction();
}
}
@Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
uiHelper.onResume();
updateUI();
}
}
(この試みでは、パラメーターのバンドルを渡しています) 2 番目に試した方法 (postStatusUpdate() メソッドだけが変更されました):
private void postStatusUpdate() {
final EditText simpleEditText = (EditText) findViewById(R.id.editStatus);
final String message = simpleEditText.getText().toString();
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");
if (canPresentShareDialog) {
FacebookDialog shareDialog = createShareDialogBuilder().build();
uiHelper.trackPendingDialogCall(shareDialog.present());
}
else if (user != null && hasPublishPermission()) {
Session session = Session.getActiveSession();
Request request = new Request(session,"me/feed",postParams,HttpMethod.POST);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
else {
pendingAction = PendingAction.POST_STATUS_UPDATE;
}
}