2014-02-24 44 views
0

我試圖獲取用戶名和我的Facebook賬戶的用戶ID,使用Android版的Facebook SDK,我使用這個代碼片段:Android的Facebook的處理會話

final Session session = Session.getActiveSession(); 
    if (session != null && session.isOpened()) { 
     // If the session is open, make an API call to get user data 
     // and define a new callback to handle the response 
     Request request = Request.newMeRequest(session, new Request.GraphUserCallback() { 
      @Override 
      public void onCompleted(GraphUser user, Response response) { 
       // If the response is successful 
       if (session == Session.getActiveSession()) { 
        if (user != null) { 
         user_ID = user.getId();//user id 
         profileName = user.getName();//user's profile name 
         userNameView.setText(user.getName()); 
        } 
       } 
      } 
     }); 
     Request.executeBatchAsync(request); 
    } 

的問題是,會話null,我應該如何處理會話管理?我的意思是激活會話的代碼和停用會話的代碼? 我想要處理給Facebook自己用自己的退出按鈕,登錄的會議,但沒有找到代碼管理會話。

非常感謝提前!

回答

1

Session.getActiveSession()null怎麼一回事,因爲你沒有正確初始化會話。 看看下面的代碼:

public class MyActivity extends Activity { 

private UiLifecycleHelper uiHelper; 
    private Session.StatusCallback callback = new Session.StatusCallback() { 
     @Override 
     public void call(final Session session, final SessionState state, final Exception exception) { 
     /** If your session status has changed you can dead with that using this callback. */ 
     } 
    }; 

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
     // Your code goes here 

     /* Initializing a valid session. */ 
     uiHelper = new UiLifecycleHelper(this, callback); //callback can be null 
     uiHelper.onCreate(savedInstanceState); 

     Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS); 
    } 

@Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     uiHelper.onActivityResult(requestCode, resultCode, data);} 
    } 

@Override 
    protected void onPause() { 
    super.onPause(); 
    uiHelper.onPause(); 
    } 

@Override 
    protected void onStop() { 
    super.onStop(); 
    Session.getActiveSession().removeCallback(callback); 
    } 

    @Override 
    public void onDestroy() { 
    super.onDestroy(); 
    uiHelper.onDestroy(); 
    } 
} 

讓我知道,如果這是有用的給你。

+0

所以我需要使用UiLifecycleHelper處理的Facebook的會議? – TiagoM

+1

@DinkLink,是的!看看Facebook的開源SDK,你會意識到,'UiLifecycleHelper'創建一個新的會話。 – yugidroid

+0

什麼是onActivityResult方法? – TiagoM