Sharing a global facebook object across Android activities

房东的猫 提交于 2019-12-06 08:12:51

问题


I'm creating a global Facebook object (from android-facebook-sdk) to be able to share it across my activities:

public class GlobalVars extends Application {

    public static final String APP_ID = "123456789";    
    public Facebook facebook = new Facebook(APP_ID);

}

In one of the activities I add the LoginButton, as shown in the examples:

public class FacebookActivity extends Activity {

    private LoginButton mLoginButton;

    private Facebook mFacebook;    
    private AsyncFacebookRunner mAsyncRunner;    

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        mFacebook = ((GlobalVars)getApplicationContext()).facebook;

        setContentView(R.layout.facebook);
        mLoginButton = (LoginButton) findViewById(R.id.login);
        mText = (TextView) FacebookActivity.this.findViewById(R.id.txt);

        mAsyncRunner = new AsyncFacebookRunner(mFacebook);

        SessionStore.restore(mFacebook, this);
        SessionEvents.addAuthListener(new SampleAuthListener());
        SessionEvents.addLogoutListener(new SampleLogoutListener());
        mLoginButton.init(this, mFacebook);

    }

    ...

}

Now, when I login and go to another activity using the same Facebook object:

public class MainActivity extends WhipemActivity {


    private Facebook mFacebook;    
    private AsyncFacebookRunner mAsyncRunner;   

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        mFacebook = ((GlobalVars)getApplicationContext()).facebook;

    }

    ....

}

and run a request such as:

mAsyncRunner = new AsyncFacebookRunner(mFacebook);
mAsyncRunner.request("me/friends", new FriendRequestListener());

I get a

Facebook Error: Error validating access token.

What's wrong? Is it the correct way to have a global Facebook object?

Thanks.


回答1:


jul, in your new activity, you need to restore the access token obtained during login.

SessionStore.restore(mFacebook, this);

SessionStore saves & restores the access token to/from SharedPreferences via a SharedPreferences object it creates.

SessionStore.restore() gets the access token saved in SharedPreferences and sets it on the Facebook object.

You can look in the "Facebook Example Simple" project and look at the SessionStore class to better see how SessionStore works.

facebook-android-sdk/examples/simple



来源:https://stackoverflow.com/questions/5276354/sharing-a-global-facebook-object-across-android-activities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!