gpt4 book ai didi

android - Firebase Auth 获取额外的用户信息(年龄、性别)

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:44:08 31 4
gpt4 key购买 nike

我正在为我的 Android 应用程序使用 Firebase 身份验证。用户可以通过多个提供商(Google、Facebook、Twitter)登录。

成功登录后,有没有办法使用 Firebase api 从这些提供商处获取用户性别/出生日期?

最佳答案

不幸的是,Firebase 没有任何内置功能可以在成功登录后获取用户的性别/生日。您必须自己从每个提供商处检索这些数据。

以下是使用 Google People API 从 Google 获取用户性别的方法

public class SignInActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
View.OnClickListener {
private static final int RC_SIGN_IN = 9001;

private GoogleApiClient mGoogleApiClient;

private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;

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

// We can only get basic information using FirebaseAuth
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in to Firebase, but we can only get
// basic info like name, email, and profile photo url
String name = user.getDisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();

// Even a user's provider-specific profile information
// only reveals basic information
for (UserInfo profile : user.getProviderData()) {
// Id of the provider (ex: google.com)
String providerId = profile.getProviderId();
// UID specific to the provider
String profileUid = profile.getUid();
// Name, email address, and profile photo Url
String profileDisplayName = profile.getDisplayName();
String profileEmail = profile.getEmail();
Uri profilePhotoUrl = profile.getPhotoUrl();
}
} else {
// User is signed out of Firebase
}
}
};

// Google sign-in button listener
findViewById(R.id.google_sign_in_button).setOnClickListener(this);

// Configure GoogleSignInOptions
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.server_client_id))
.requestServerAuthCode(getString(R.string.server_client_id))
.requestEmail()
.requestScopes(new Scope(PeopleScopes.USERINFO_PROFILE))
.build();

// Build a GoogleApiClient with access to the Google Sign-In API and the
// options specified by gso.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addOnConnectionFailedListener(this)
.addConnectionCallbacks(this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.google_sign_in_button:
signIn();
break;
}
}

private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}

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

// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Signed in successfully
GoogleSignInAccount acct = result.getSignInAccount();

// execute AsyncTask to get gender from Google People API
new GetGendersTask().execute(acct);

// Google Sign In was successful, authenticate with Firebase
firebaseAuthWithGoogle(acct);
}
}
}

class GetGendersTask extends AsyncTask<GoogleSignInAccount, Void, List<Gender>> {
@Override
protected List<Gender> doInBackground(GoogleSignInAccount... googleSignInAccounts) {
List<Gender> genderList = new ArrayList<>();
try {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

//Redirect URL for web based applications.
// Can be empty too.
String redirectUrl = "urn:ietf:wg:oauth:2.0:oob";

// Exchange auth code for access token
GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(
httpTransport,
jsonFactory,
getApplicationContext().getString(R.string.server_client_id),
getApplicationContext().getString(R.string.server_client_secret),
googleSignInAccounts[0].getServerAuthCode(),
redirectUrl
).execute();

GoogleCredential credential = new GoogleCredential.Builder()
.setClientSecrets(
getApplicationContext().getString(R.string.server_client_id),
getApplicationContext().getString(R.string.server_client_secret)
)
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.build();

credential.setFromTokenResponse(tokenResponse);

People peopleService = new People.Builder(httpTransport, jsonFactory, credential)
.setApplicationName("My Application Name")
.build();

// Get the user's profile
Person profile = peopleService.people().get("people/me").execute();
genderList.addAll(profile.getGenders());
}
catch (IOException e) {
e.printStackTrace();
}
return genderList;
}

@Override
protected void onPostExecute(List<Gender> genders) {
super.onPostExecute(genders);
// iterate through the list of Genders to
// get the gender value (male, female, other)
for (Gender gender : genders) {
String genderValue = gender.getValue();
}
}
}
}

您可以在 Accessing Google APIs 上找到更多信息

关于android - Firebase Auth 获取额外的用户信息(年龄、性别),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39249043/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com