我正在使用来自CONTACTS组的GET_ACCOUNTS权限,并在我的代码中处理它。我只是无法弄清楚为什么帐户名称在设置后仍为空。该应用程序已拥有权限,因为没有弹出对话框告诉用户授予权限。
我在onCreate中设置了凭证,如下所示:
mCredential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
这是我试图设置名称的地方:
/**
* Attempts to set the account used with the API credentials. If an account
* name was previously saved it will use that one; otherwise an account
* picker dialog will be shown to the user. Note that the setting the
* account to use with the credentials object requires the app to have the
* GET_ACCOUNTS permission, which is requested here if it is not already
* present. The AfterPermissionGranted annotation indicates that this
* function will be rerun automatically whenever the GET_ACCOUNTS permission
* is granted.
*/
@AfterPermissionGranted(REQUEST_PERMISSION_GET_ACCOUNTS)
private void chooseAccount() {
if (EasyPermissions.hasPermissions(
this, Manifest.permission.GET_ACCOUNTS)) {
String accountName = getPreferences(Context.MODE_PRIVATE)
.getString(PREF_ACCOUNT_NAME, null);
if (accountName != null) {
mCredential.setSelectedAccountName(accountName); // I set the account name here
Log.d("MESSAGE", accountName); // this prints out the account name as an email
Log.d("MESSAGE", mCredential.getSelectedAccountName()); // this throws a null pointer
getResultsFromApi();
} else {
// Start a dialog from which the user can choose an account
Log.d("MESSAGE", "Start dialogue box to select account");
startActivityForResult(
mCredential.newChooseAccountIntent(),
REQUEST_ACCOUNT_PICKER);
}
} else {
// Request the GET_ACCOUNTS permission via a user dialog
Log.d("MESSAGE", "Creates dialogue box to request permission");
EasyPermissions.requestPermissions(
this,
"This app needs to access your Google account (via Contacts).",
REQUEST_PERMISSION_GET_ACCOUNTS,
Manifest.permission.GET_ACCOUNTS);
}
}
以下是我对Manifest文件的权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
这是我的第一个项目,我不是很有经验。任何帮助将不胜感激!!
答案 0 :(得分:1)
我有同样的问题。用户setSelectedAccount()而不是setSelectedAccountName()。
mCredential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
// to set accountName manually instead of prompting user to select it
mCredential.setSelectedAccount(new Account("xyz@gmail.com", "come.android.example"));
将gmail帐户作为第一个参数,将您的包名称作为第二个参数。它应该工作。