我已经按照facebook开发人员教程登录app。
我使用过这段代码,效果很好:
public class MainActivity extends AppCompatActivity {
LoginButton loginButton;
TextView textView;
CallbackManager callbackManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
loginButton=(LoginButton)findViewById(R.id.fb_login_bn);
textView=(TextView)findViewById(R.id.textView);
loginButton.setReadPermissions(Arrays.asList(
"public_profile", "email", "user_birthday", "user_friends"));
callbackManager=CallbackManager.Factory.create();
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
// Facebook Email address
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
Log.v("LoginActivity Response ", response.toString());
try {
String Name = object.getString("name");
String FEmail = object.getString("email");
Log.v("Email = ", " " + FEmail);
Intent i = new Intent(MainActivity.this, Vote.class);
startActivity(i);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
@Override
public void onCancel() {
textView.setText("Login cancelled");
}
@Override
public void onError(FacebookException error) {
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode,resultCode,data);
}
但是如何保存用户登录会话以便用户第二次不签名?
如何将用户的姓名和电子邮件传递给其他活动?
答案 0 :(得分:0)
如何将用户的姓名和电子邮件传递给其他活动
使用intent.putExtra()
在您的MainActivity
传递数据
String Name = object.getString("name");
String FEmail = object.getString("email");
Log.v("Email = ", " " + FEmail);
Intent i = new Intent(MainActivity.this, Vote.class);
i.putExtra("name", Name);
i.putExtra("email", FEmail);
startActivity(i);
在Vote
课程中使用以下方式获取价值:
String name = getIntent().getStringExtra("name");
String email = getIntent().getStringExtra("email");
如何保存用户登录会话以便用户不登录 第二次
使用SharedPreferences
检查用户是否已登录
成功登录后,将值保存到sharedpreferences
:
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences prefs = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean("logged_in", true); //save value
editor.commit();
您可以从sharedpreference
检索值并检查用户是否已登录并执行所需操作。
if (prefs.getBoolean("logged_in", false)) {
//user logged in before
} else {
//not logged in
}