简体   繁体   中英

How to log in to facebook on android

I have tried the tutorial http://developers.facebook.com/docs/mobile/android/build/#sdk and I am able to login successfully. this code provides a dialog to login. But I want to make this as an Activity . Because I have to perform other tasks too from this activity. Like when new activity starts after sucessful login come back to previous (facebook) activity again in previous state of facebook. Please help me. Thanks

The dialog is only created for the user to log into Facebook. Once they have done that it will return back to the original activity. This is what you are asking for right?

Lets say you want to post a message to facebook.

try {
        Log.d(TAG, "postToFaceBook()");
        if (facebook == null) {
            facebook = new Facebook(API);
            String access_token = prefs.getFBAccesTocken();

            long expires = prefs.getFBExpiry();
            if (access_token != null) {
                facebook.setAccessToken(access_token);
            }
            if (expires != 0) {
                facebook.setAccessExpires(expires);
            }
        }

        if (facebook.isSessionValid()) {
            Log.d(TAG, "Session is valid");
            facebook.extendAccessTokenIfNeeded(this, null);
            postToFacebook();
        } else {
            Log.d(TAG, "not valid");
            // Using SSO OAuth
            // facebook.authorize(this, new String[] { "publish_stream"
            // },new LoginDialogListener());

            // Not using SSO
            facebook.authorize(this, new String[] { "publish_stream" },
                    Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
        }
    } catch (NullPointerException e) {
        Log.e(TAG, "An error occurd trying to open facebook app");

If the user has logged onto facebook in the past and has a valid session, it will simply post to Facebook if there is not a valid session it will open up the dialog and try to log in.

The LoginDialogListener() responds to the response of this.

public class LoginDialogListener extends BaseDialogListener {

    @Override
    public void onComplete(Bundle values) {
        Log.d(TAG, "Login response recieved");
        prefs.saveToken(facebook.getAccessToken());
        prefs.saveExpiry(facebook.getAccessExpires());
        facebook.extendAccessTokenIfNeeded(MyActivity.this, null);
        Log.d(TAG, "Logged in ");
        postToFacebook();
    }

}

The other option is to look at using SSO (which I have commented out in the example code).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM