I'm looking to pass a Facebook session across activities. I saw the example from Facebook's SDK and someone mentioned that the "Simple" example has a way to do this: https://github.com/facebook/facebook-android-sdk/blob/master/examples/simple/src/com/facebook/android/SessionStore.java
But how does this work? In my MainActivity
, I have this:
mPrefs = getPreferences(MODE_PRIVATE);
String accessToken = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (accessToken != null) {
//We have a valid session! Yay!
facebook.setAccessToken(accessToken);
}
if (expires != 0) {
//Since we're not expired, we can set the expiration time.
facebook.setAccessExpires(expires);
}
//Are we good to go? If not, call the authentication menu.
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] { "email", "publish_stream" }, new DialogListener() {
@Override
public void onComplete(Bundle values) {
}
@Override
public void onFacebookError(FacebookError error) {
}
@Override
public void onError(DialogError e) {
}
@Override
public void onCancel() {
}
});
}
But how do I pass this along to my PhotoActivity
activity? Is there an example of this being implemented?
Using SharedPreferences to pass data across activities is not good idea. SharedPreferences used to store some data into memory across application restart or device re-boot.
Instead you have two options:
Declare a static variable to hold facebook session, which is simplest method, but I wont recommend to use Static Fields as far there is no other way.
Make an class implementing parcelable, and set your facebook object there, see an parcelable implementation as follows:
The example pretty much has the whole implementation. You just use
SharedPreferences
to store your session. When you need it in your PhotoActivity, just look inSharedPreferences
again (perhaps via yourSessionStore
static methods if you followed the same pattern) to get the Facebook Session that you previously stored.For FB SDK 3.5, In my FB login activity, I pass the active session object via intent extras because the Session class implements serializable:
From my MainActivity onCreate(), I check for intent extra and initiate the session: