How can I get the google username on Android?
I've seen references to using the AccountManager
like Accessing Google Account Id /username via Android. But it seems like it's for grabbing the authtoken
?
I just need access to the u开发者_Go百科sername, no passwords or any auth tokens.
I'm using android 2.1 sdk. How can I get the google username on Android?
As mentioned in the comments, Roman's answer to How to get the Android device's primary e-mail address solves it. Here's the code i used that will also strip out the username from the email.
public String getUsername() {
AccountManager manager = AccountManager.get(this);
Account[] accounts = manager.getAccountsByType("com.google");
List<String> possibleEmails = new LinkedList<String>();
for (Account account : accounts) {
// TODO: Check possibleEmail against an email regex or treat
// account.name as an email address only for certain account.type values.
possibleEmails.add(account.name);
}
if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
String email = possibleEmails.get(0);
String[] parts = email.split("@");
if (parts.length > 1)
return parts[0];
}
return null;
}
In new Android version you can't get the accounts with code due to security reason:-
it needs to be prompt to user, and if user agreed then only can be proceed with it.The code will be looks like below :-
private val chooseAccount = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ result: ActivityResult ->
result.apply {
if (resultCode == RESULT_OK) {
Timber.d("resultCode ==RESULT_OK")
Timber.d(data?.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE))
Timber.d(data?.getStringExtra(AccountManager.KEY_ACCOUNT_NAME))
} else if (resultCode == RESULT_CANCELED) {
Timber.d("resultCode ==RESULT_CANCELED")
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
//Note: setAllowableAccountsTypes you can change it as per your need
chooseAccount.launch(
AccountPicker.newChooseAccountIntent(
AccountPicker.AccountChooserOptions.Builder()
.setAllowableAccountsTypes(listOf(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE))
.setAlwaysShowAccountPicker(true)
.build()
))
}
精彩评论