隨着@ Anyonymous2324的幫助下,我找到了解決方案。除了下面的答案中提到的內容,還有更多的事情要做。所以我認爲對未來在這裏磕磕絆絆的人是最好的;如果我把它放在一起。
要獲得帳戶名(電子郵件)或顯示名稱(用戶名),所需的代碼是由@ Anyonymous2324
Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String accountName = Plus.AccountApi.getAccountName(mGoogleApiClient);
但要得到這個工作,有幾件事情是提到的相同需要完成。
- 轉到Developer's console並添加Google+的API爲你的項目(這是需要使用任何Google+的相關工作,在我們的情況下,它收集用戶名)。
- 我們需要添加權限以訪問設備的帳戶,方法是在清單中添加
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
。
- 在你
GoogleApiClient.Builder
加上加API這樣.addApi(Plus.API)
- 我們還需要添加一些範圍,以使
getDisplayName
可以工作。這些是.addScope(Plus.SCOPE_PLUS_LOGIN)
和.addScope(Plus.SCOPE_PLUS_PROFILE)
要提及here該getCurrentPerson
方法可以返回null
如果未指定的需要的範圍或有一個網絡故障。因此最好在調用getDisplayName
之前檢查currentPerson
對象。然後 完整的代碼如下:
Person currentPerson = Plus.PeopleApi.getCurrentPerson(mClient);
if(currentPerson != null) {
String currentPersonName = currentPerson.getDisplayName();
Log.d(TAG, currentPersonName);
logStatus(currentPersonName);
}
由於文檔中提到的返回值可以在網絡錯誤的情況下空;爲INTERNET添加權限似乎是一個好主意。但在我的手機上,它沒有連接互聯網。我想這是從我手機上的Google+應用中獲取信息,而不是完全上網,所以我不必使用互聯網。
但不要拿我的話來測試自己。
我能夠成功獲取AccountName,但沒有DisplayName。我得到java.lang.NullPointerException:嘗試調用空對象引用上的接口方法'java.lang.String com.google.android.gms.plus.model.people.Person.getDisplayName()' – Ishan
這裏是變化我提出https://github.com/ishanatmuz/GoogleFitTest/commit/967df7bd214fe2f0d8125fd44c2fb877adb5a582 – Ishan
'Plus.PeopleApi.getCurrentPerson()'可能返回null,因爲您沒有權限查看用戶的詳細信息。在構建'GoogleApiClient'時,請確保添加正確的範圍。看到這裏:https://developer.android.com/reference/com/google/android/gms/common/api/GoogleApiClient.Builder.html – Anyonymous2324