如何在使用 Firebase 登录 Facebook 后显示带有 displayName 的 Toast 消息?



在我的应用程序中,可以使用Facebook登录,成功登录后,我想显示一条吐司消息,上面写着"欢迎回来,用户名(这是显示名称("。我设法显示一条消息,但没有用户名,因为我不知道如何从Firebase获取并在登录后显示它。

以下是处理Facebook登录的代码:

private void handleFacebookAccessToken(AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
progressBar.setVisibility(View.VISIBLE);

AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
// Todo make a toast with the username
Toast.makeText(SignInActivity.this, "Welcome back", Toast.LENGTH_SHORT).show();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(SignInActivity.this, "Error.",
Toast.LENGTH_LONG).show();
updateUI(null);
}
progressBar.setVisibility(View.INVISIBLE);
}
});
}

一旦你有了Facebook的访问令牌,你就可以使用GraphApi来获取用户的其他信息:

val request = GraphRequest.newMeRequest(
accessToken
) { user, _ ->
try {
val name = user.getString("name")
Toast.makeText(context, "Hello, $name!", Toast.LENGTH_SHORT).show()
} catch (e: JSONException) {
Timber.d("Unable to get user name")
}
}
val parameters = Bundle()
parameters.putString("fields", "name")
request.parameters = parameters
request.executeAsync()

这是 java 中的代码片段

public void requestData(){
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object,GraphResponse response) {
JSONObject json = response.getJSONObject();
try {
if(json != null){
String name = user.getString("name");
Toast.makeText(context, "Welcome "+name, Toast.LENGTH_SHORT).show()
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,email,picture");
request.setParameters(parameters);
}

最新更新