可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
回答1:
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()"
回答2:
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
回答3:
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());
回答4:
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();
回答5:
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());
}
/***/
}
回答6:
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.