1
我正在使用CONTACTS組中的GET_ACCOUNTS權限,並且還在我的代碼中處理它。我只是不知道爲什麼帳戶名稱設置後仍爲空。該應用程序已具有權限,因爲沒有彈出對話框來告訴用戶授予權限。GoogleAccountCredential getSelectedAccountName()在設置並執行權限後返回空值
我將憑證在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);
}
}
以下是清單文件我的權限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
這是我第一個項目,我不是很有經驗。任何幫助將不勝感激!!
您正在使用首選項來獲取帳戶名稱,但您尚未將其保存在任何地方。你有沒有把它保存在偏好中? –
是的,它保存在首次啓動應用程序時調用的方法中創建的首選項。它在從用戶請求帳戶名稱後,將該帳戶名稱保存在該首選項中。上述方法訪問已存在的首選項。帳戶名稱保存在字符串中。它只是不會讓我把它設置爲憑證。 –
在mCredential.setSelectedAccountName(accountName)中傳遞它之前,accountName的值是多少? ? – noogui