With the help of @Anyonymous2324 I figured out the solution. There is little more to do than what's mentioned in the answer below. So I thought it would be best for anyone who stumbles upon here in future; if I put it all together.
To get the accountName (email) or Display Name (user's name), the code required is the same as mentioned by @Anyonymous2324
Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String accountName = Plus.AccountApi.getAccountName(mGoogleApiClient);
But to get this to work there are a few things that are needed to be done.
- Go to Developer's console and add Google+ API for your project (This is required for the use of any Google+ related work, in our case it is gathering of user name).
- We need to add permission to access the accounts of the device, by adding
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
to the manifest.
- In your
GoogleApiClient.Builder
add the Plus API like this .addApi(Plus.API)
- We also need to add some scopes so that
getDisplayName
can work. These are .addScope(Plus.SCOPE_PLUS_LOGIN)
and .addScope(Plus.SCOPE_PLUS_PROFILE)
It is mentioned here that the getCurrentPerson
method can return null
if the required scopes are not specified or there is a network failure. Therefore it is better to check the currentPerson
object before calling getDisplayName
on it.
The complete code then looks like :
Person currentPerson = Plus.PeopleApi.getCurrentPerson(mClient);
if(currentPerson != null) {
String currentPersonName = currentPerson.getDisplayName();
Log.d(TAG, currentPersonName);
logStatus(currentPersonName);
}
Since the documentation mentions that the returned value can be null in case of network error; adding permission for INTERNET seems like a good idea. But on my phone it was working without the internet connection. I guess it was taking the information from Google+ app on my phone and not going to the internet altogether, so I didn't had to use internet.
But don't take my word on it and test yourself.