如果您在 Facebook 类上设置了打开的 Session,则 dialog() 不应提示用户登录。
这是一个例子:
public class MainActivity extends Activity {
boolean pendingShare;
Session session;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (savedInstanceState != null) {
pendingShare = savedInstanceState.getBoolean("pendingShare");
session = Session.restoreSession(this, null, new SessionCallback(), savedInstanceState);
}
((Button) findViewById(R.id.share_button)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onClickShare();
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("pendingShare", pendingShare);
Session.saveSession(session, outState);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (session != null) {
session.onActivityResult(this, requestCode, resultCode, data);
}
}
private void onClickShare() {
pendingShare = true;
session = new Session(MainActivity.this);
session.openForRead(new Session.OpenRequest(MainActivity.this).setCallback(new SessionCallback()));
}
private void share(Session session) {
Facebook facebook = new Facebook(session.getApplicationId());
facebook.setSession(session);
facebook.dialog(this, "feed", null);
pendingShare = false;
}
class SessionCallback implements Session.StatusCallback {
@Override
public void call(Session session, SessionState state, Exception exception) {
if (state.isOpened() && pendingShare) {
share(session);
}
}
}
}
保存/恢复“pendingShare”(和会话)在这里很有用,因为您的 Activity 可以在登录期间卸载,这会记住在重新加载 MainActivity 时触发 dialog() 调用。