【发布时间】:2018-01-10 01:32:09
【问题描述】:
我正在使用来自 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" />
这是我的第一个项目,我不是很有经验。任何帮助将不胜感激!
【问题讨论】:
-
您正在使用首选项来获取帐户名称,但您尚未将其保存在任何看起来的地方。不过,您是否已将其保存在首选项中?
-
是的,它保存在首选项中,该首选项是在第一次启动应用程序时调用的方法中创建的。在向用户请求后,它将帐户名称保存在该首选项中。上述方法访问已经存在的 Preference。帐户名称保存在字符串中。它只是不允许我将其设置为凭据。
-
在你传入 mCredential.setSelectedAccountName(accountName); 之前 accountName 的值是多少?
-
@noogui 这是我正在测试它的电子邮件。