Android: Passing a Facebook session across activit

2020-02-29 15:50发布

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?

3条回答
Fickle 薄情
2楼-- · 2020-02-29 16:26

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:

  1. 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.

  2. Make an class implementing parcelable, and set your facebook object there, see an parcelable implementation as follows:

    // simple class that just has one member property as an example
    public class MyParcelable implements Parcelable {
        private int mData;
    
        /* everything below here is for implementing Parcelable */
    
        // 99.9% of the time you can just ignore this
        public int describeContents() {
            return 0;
        }
    
        // write your object's data to the passed-in Parcel
        public void writeToParcel(Parcel out, int flags) {
            out.writeInt(mData);
        }
    
        // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
        public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {
            public MyParcelable createFromParcel(Parcel in) {
                return new MyParcelable(in);
            }
    
            public MyParcelable[] newArray(int size) {
                return new MyParcelable[size];
            }
        };
    
        // example constructor that takes a Parcel and gives you an object populated with it's values
        private MyParcelable(Parcel in) {
            mData = in.readInt();
        }
    }
    
查看更多
聊天终结者
3楼-- · 2020-02-29 16:44

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 in SharedPreferences again (perhaps via your SessionStore static methods if you followed the same pattern) to get the Facebook Session that you previously stored.

查看更多
家丑人穷心不美
4楼-- · 2020-02-29 16:48

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:

private void onSessionStateChange(Session session, SessionState state, Exception exception) {
    if (exception instanceof FacebookOperationCanceledException || exception instanceof FacebookAuthorizationException) {
        new AlertDialog.Builder(this).setTitle(R.string.cancelled).setMessage(R.string.permission_not_granted).setPositiveButton(R.string.ok, null).show();

    } else {

        Session session = Session.getActiveSession();

        if ((session != null && session.isOpened())) {
            // Kill login activity and go back to main
            finish();
            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            intent.putExtra("fb_session", session);
            startActivity(intent);
        }
    }
}

From my MainActivity onCreate(), I check for intent extra and initiate the session:

Bundle extras = getIntent().getExtras();
if (extras != null) {           
    Session.setActiveSession((Session) extras.getSerializable("fb_session"));
}
查看更多
登录 后发表回答