我正在使用 Google+ Sign-In在我的 Android 应用程序中。如何获取经过身份验证的用户帐户的域?它不是 com.google.android.gms.plus.model.people.Person 模型的属性。
具体来说,我只希望一家公司的人能够使用他们的工作 Google 帐户访问该应用程序(公司中的每个人都有一个)。
我当然可以使用 Plus.AccountApi.getAccountName(mGoogleApiClient);
检索电子邮件地址并且可以检查电子邮件地址的域,但这看起来很讨厌。
最佳答案
您试图在流程中的错误时间过滤帐户域。您应该在用户登录之前进行检查。
为此,请检索系统上的所有帐户并检查符合条件的帐户,并且只有在找到合适的帐户后才能登录。
获取所有帐户并对其进行过滤的简单 Activity 可能如下所示:
public class CheckAccounts extends AppCompatActivity {
private static final int MY_PERMISSIONS_REQUEST_GET_ACCOUNTS = 8;
final String TAG = this.getClass().toString();
private void getPermissions() {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.GET_ACCOUNTS)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.GET_ACCOUNTS},
MY_PERMISSIONS_REQUEST_GET_ACCOUNTS);
// MY_PERMISSIONS_REQUEST_GET_ACCOUNTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
private void getAccounts() {
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.GET_ACCOUNTS)
!= PackageManager.PERMISSION_GRANTED) {
getPermissions();
}
AccountManager accountManager = AccountManager.get(this);
Account[] accounts = accountManager.getAccountsByType("com.google");
for (Account a : accounts){
String accountName = a.name;
String domain = accountName.substring(accountName.indexOf("@") + 1, accountName.length());
Log.d(TAG, "account domain: " + domain);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_accounts);
getAccounts();
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_GET_ACCOUNTS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getAccounts();
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
Log.d(TAG, "didn't get perms");
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
找到合适的帐户后,您可以使用 GoogleSignInOptions.Builder setAccountName使用此特定帐户登录。如果您在设备上找不到合适的帐户,您可以简单地通知用户,而不是先登录他或她的帐户。
问候,
米尔科
关于android - 在 Android 中获取 Google 帐户域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30470659/