17

我一直在通过 Facebook 最新的 SDK 即 3.0 做一些登录项目。我很难获得用户访问令牌。我在互联网上搜索过,所有最大的结果都是使用旧的 SDK。这是我从Facebook Android SDK 教程中获取的一些代码:

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() + "!");
                                }
                            }
                        });
            }
        }
    });

}

}

登录成功,我可以在应用程序中看到用户名,正如 Facbeook 教程所建议的那样。

我尝试过旧方法,但现在都已弃用。请指导我获取用户访问令牌。帮助将不胜感激。

谢谢。

4

6 回答 6

39

在 onResume() 方法中添加以下代码(在这种情况下,我使用 Toast.makeText 来查看登录后的令牌访问):

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

我使用 getActivity 是因为它在我的情况下位于 Fragment 中,如果您在 Activity 中有登录按钮,请使用“this”而不是“getActivity()”

于 2013-02-21T18:52:39.413 回答
33

注意:新的 Facebook sdk 中删除了 Session 类

之后Facebook SDK version 4.X,您应该使用以下内容:

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

更改日志参考在这里。

将参考从 Sdk 3.x 迁移到 4.x

于 2015-05-26T07:44:56.037 回答
5

我是 Android 新手 ..
我使用上面的代码只获取令牌。

对于 Facebook SDK 4.21.0
编译 '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());
于 2017-04-08T10:57:29.313 回答
3

获取 facebook-sdk 4.* 或更高版本的 accessToken。在 facebookSDKInitialize() 之后添加此行

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

之后使用这些代码行,

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

样本:

 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();
于 2016-09-09T05:28:01.810 回答
0

以下代码已更新:

@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());
    }
    /***/
}
于 2017-02-13T13:54:58.777 回答
-3

在以下代码的帮助下,我成功地将 Facebook sdk 集成到我的我的中:

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);
    }
}

我希望,你会得到一些帮助。

于 2013-02-21T07:44:16.270 回答