17

I have been doing some login project via Facebook latest SDK i.e. 3.0. I'm getting a hard time in getting user access token. I have searched on the internet and all, maximum results were using the old SDK. Here is some bits of code which I have taken from Facebook Android SDK Tutorial:

public class LoginActivity extends Activity implements OnClickListener {

Button login;
TextView accessToken;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    login = (Button) findViewById(R.id.login);
    accessToken = (TextView) findViewById(R.id.accessToken);

    login.setOnClickListener(this);

}

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

@Override
public void onClick(View v) {
    // start Facebook Login
    Session.openActiveSession(this, true, new Session.StatusCallback() {

        // callback when session changes state
        @Override
        public void call(Session session, SessionState state,
                Exception exception) {
            if (session.isOpened()) {

                // make request to the /me API
                Request.executeMeRequestAsync(session,
                        new Request.GraphUserCallback() {

                            // callback after Graph API response with user
                            // object
                            @Override
                            public void onCompleted(GraphUser user,
                                    Response response) {
                                if (user != null) {
                                    TextView welcome = (TextView) findViewById(R.id.welcome);
                                    welcome.setText("Hello "
                                            + user.getName() + "!");
                                }
                            }
                        });
            }
        }
    });

}

}

Login was successful and I can see Username in the app, as suggested by the Facbeook tutorial.

I have tried old methods, but those all are now deprecated. Please guide me in getting User Access Token. Help will be appreciated.

Thanks.

Anupam
  • 3,632
  • 18
  • 53
  • 87

6 Answers6

39

In the method onResume() add the following code (in this case i used Toast.makeText to see the token access after login):

    Session session = Session.getActiveSession();
    if (session.isOpened()) {
        Toast.makeText(getActivity(), session.getAccessToken(), Toast.LENGTH_LONG).show();
    }

I used getActivity because it is in a Fragment in my case, if you have your login button in an Activity use "this" instead of "getActivity()"

  • When you look at the session, it seems as if the token would have been removed, as it displays `token:{ACCESS_TOKEN REMOVED}`, but `session.getAccessToken()` correctly retrieves the token. – Oliver Hausler Feb 16 '15 at 18:28
33

Note: Session class is removed in new Facebook sdk

After Facebook SDK version 4.X, you should use following:

AccessToken token = AccessToken.getCurrentAccessToken();
if (token != null) {
    Toast.makeText(getActivity(), token, Toast.LENGTH_LONG).show();
}

Change log reference is here.

Migrate reference from Sdk 3.x to 4.x

uniruddh
  • 4,218
  • 3
  • 47
  • 85
  • @astuter, how do we get notified when first time app logged in with FB and onActivityResult is called ? For me, onSuccess() of registerCallback(callbackManager, new FacebookCallback() {} is not called though I called callBackmanager.onActivityResult() in onActivityResult() of my activity. ANy clue ? – cgr Jan 04 '16 at 15:27
  • 1
    i think that token shold be changed to token.getToken(), – Youness Jul 13 '16 at 13:38
  • 1
    @youness you are right. The answer above needs to be updated. I posted an updated answer to this question below. – Marcelo Gumiero Feb 13 '17 at 13:57
5

I'm new in Android ..
I'm using the above code for getting the token only.

For Facebook SDK 4.21.0
compile 'com.facebook.android:facebook-android-sdk:4.21.0'

FacebookSdk.setIsDebugEnabled(true);              
FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

AccessToken token = AccessToken.getCurrentAccessToken();
Log.d("access only Token is", String.valueOf(token.getToken()));
String facebook_id_token = String.valueOf(token.getToken());
Sujeet Kumar
  • 1,562
  • 15
  • 23
3

To get the accessToken for facebook-sdk 4.* or above. Add this lines after facebookSDKInitialize()

FacebookSdk.setIsDebugEnabled(true);
FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKEN);

After that use these lines of codes,

AccessToken token = AccessToken.getCurrentAccessToken();
Log.d("Access Token is",token);

Sample:

 GraphRequestAsyncTask graphRequestAsyncTask = new GraphRequest(
    login_result.getAccessToken(),
    //AccessToken.getCurrentAccessToken(),
    "/me/friends",
    bundle,
    HttpMethod.GET,
    new GraphRequest.Callback() {
    public void onCompleted(GraphResponse response) {
    try {
    JSONArray rawName = response.getJSONObject().getJSONArray("data");
    Log.d("rawName friendList",String.valueOf(rawName));
    AccessToken token = AccessToken.getCurrentAccessToken();
    Log.d("access token is: ",String.valueOf(token));
    } catch (JSONException e) {
    e.printStackTrace();
    }
    }
    }
).executeAsync();
Rjz Satvara
  • 3,175
  • 2
  • 18
  • 41
Mukul Aggarwal
  • 1,295
  • 16
  • 13
0

Code below is updated:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);

    /** This block obtains Facebook UserID and Token */
    AccessToken token = AccessToken.getCurrentAccessToken();
    if (token != null) {
        Toast.makeText(this, token.toString(), Toast.LENGTH_SHORT).show();
        Log.e(TAG, "Token: " + token.getToken());
        Log.e(TAG, "UserID: " + token.getUserId());
    }
    /***/
}
Marcelo Gumiero
  • 1,791
  • 2
  • 10
  • 14
-3

I successfully managed to integrate the Facebook sdk in my my with the help of following code:

public class MainActivity extends Activity implements OnClickListener {
    Facebook fb;
    Button button;
    SharedPreferences sp;
    //TextView welcome;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String APP_ID = getString(R.string.APP_ID);
        fb=new Facebook(APP_ID);

        sp=getPreferences(MODE_PRIVATE);
        String access_token=sp.getString("access token",null);
        long expires=sp.getLong("access expires",0);

        if(access_token!=null){
            fb.setAccessToken(access_token);
        }
        if(expires!=0){
            fb.setAccessExpires(expires);
        }



        button=(Button)findViewById(R.id.login);
        //pic=(ImageView)findViewById(R.id.picture_pic);
        button.setOnClickListener(this);
        updateButtonImage();
    }

    private void updateButtonImage() {
        // TODO Auto-generated method stub
        if(fb.isSessionValid()){
            try{
                //post.setVisibility(Button.VISIBLE);
                button.setBackgroundResource(R.drawable.logout_button);
                /*pic.setVisibility(ImageView.VISIBLE);

                JSONObject obj=null;
                URL img_url = null;
                String jsonuser=fb.request("me");
                obj=Util.parseJson(jsonuser);

                String id = obj.optString("id");
                String name = obj.optString("name");
                welcome.setText("Welcome  "+name);
                img_url=new URL("http://graph.facebook.com/"+id+"/picture?type=large");
                Bitmap bmp =  BitmapFactory.decodeStream(img_url.openConnection().getInputStream());
                pic.setImageBitmap(bmp);*/
                buttonClicks();
                }catch(Exception e){
                    e.printStackTrace();
                }

        }else{
            //post.setVisibility(Button.INVISIBLE);
            button.setBackgroundResource(R.drawable.login_button);
            //pic.setVisibility(ImageView.INVISIBLE);
        }
    }

    public void buttonClicks()
    {
            Bundle params = new Bundle();
            params.putString("image", "your string");


            fb.dialog(MainActivity.this, "feed", params, new DialogListener(){

                @Override
                public void onComplete(Bundle values) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onFacebookError(FacebookError e) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onError(DialogError e) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onCancel() {
                    // TODO Auto-generated method stub

                }

            });
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if(fb.isSessionValid()){
            //button close our session - log out facebook
            try {
                fb.logout(getApplicationContext());
                updateButtonImage();
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else{
            //login to fb
            fb.authorize(MainActivity.this, new String[] {"email"}, new DialogListener(){

                @Override
                public void onComplete(Bundle values) {
                    // TODO Auto-generated method stub
                    Editor editor=sp.edit();
                    editor.putString("access_token", fb.getAccessToken());
                    editor.putLong("access expires", fb.getAccessExpires());
                    editor.commit();
                    updateButtonImage();
                }

                @Override
                public void onFacebookError(FacebookError e) {
                    // TODO Auto-generated method stub
                    Toast.makeText(MainActivity.this, "onFacebookError", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onError(DialogError e) {
                    // TODO Auto-generated method stub
                    Toast.makeText(MainActivity.this, "onError", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onCancel() {
                    // TODO Auto-generated method stub
                    Toast.makeText(MainActivity.this, "onCancel", Toast.LENGTH_SHORT).show();
                }

            });
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        fb.authorizeCallback(requestCode, resultCode, data);
    }
}

I hope, you will get some help with this.

Rohit
  • 500
  • 3
  • 15
  • I just need to get access token, when login is complete. Can you help me with that. I think you have used the old FB SDK. Or you have implemented using the new FB SDK i.e. FacebookSDK-3.0? – Anupam Feb 21 '13 at 08:51
  • I used facebook SDK 3.0. Here is the link in which methods are described how to get Access Token. http://developers.facebook.com/docs/reference/android/3.0/AccessToken – Rohit Feb 21 '13 at 10:41
  • 1
    Rohit, you'll probably see that your code fails to get the access token when a user 1) installs your app and grants FB access, then 2) uninstalls your app, then 3) reinstalls your app. – Someone Somewhere Aug 08 '13 at 19:58