如果您需要请求扩展权限,可以按照此处的指南进行操作。从帖子:
让我们首先定义我们需要什么权限
// List of additional write permissions being requested
private static final List<String> PERMISSIONS = Arrays.asList("publish_stream, publish_actions");
// Request code for reauthorization requests.
private static final int REAUTH_ACTIVITY_CODE = 100;
// Flag to represent if we are waiting for extended permissions
private boolean pendingAnnounce = false;
我们将首先检查我们是否拥有所有必需的权限。如果没有,我们使用我们请求的权限集创建一个新的 ReauthorizeRequest。这会将我们应用之外的用户引导至 Facebook 应用或浏览器以确认权限。当用户确认请求时,他将被重定向回我们的应用程序,并调用调用重新授权请求的 Activity 的 onActivityResult。
private void handleAnnounce() {
pendingAnnounce = false;
Session session = Session.getActiveSession();
if (session == null || !session.isOpened()) {
return;
}
List<String> permissions = session.getPermissions();
if (!permissions.containsAll(PERMISSIONS)) {
pendingAnnounce = true; // Mark that we are currently waiting for confirmation of publish permissions
session.addCallback(this);
requestPublishPermissions(this, session, PERMISSIONS, REAUTH_ACTIVITY_CODE);
return;
}
// TODO: Publish the post. You would need to implement this method to actually post something
publishMessage();
}
void requestPublishPermissions(Activity activity, Session session, List<String> permissions,
int requestCode) {
if (session != null) {
Session.ReauthorizeRequest reauthRequest = new Session.ReauthorizeRequest(activity, permissions)
.setRequestCode(requestCode);
session.reauthorizeForPublish(reauthRequest);
}
}
如果会话状态发生变化,这将处理结果并调用 onSessionStateChanged。然后,如果我们的令牌已成功更新,我们将检查该方法并尝试再次发布消息。
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REAUTH_ACTIVITY_CODE:
Session session = Session.getActiveSession();
if (session != null) {
session.onActivityResult(this, requestCode, resultCode, data);
}
break;
}
}
protected void onSessionStateChange(final Session session, SessionState state, Exception exception) {
if (session != null && session.isOpened()) {
if (state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
// Session updated with new permissions
// so try publishing once more.
tokenUpdated();
}
}
}
/**
* Called when additional permission request is copmleted successfuly.
*/
private void tokenUpdated() {
// Check if a publish action is in progress
// awaiting a successful reauthorization
if (pendingAnnounce) {
// Publish the action
handleAnnounce();
}
}