Instead of using Googles People API classes to access their REST service I find it much simpler to just access the service directly.
Also saves 1.5 MB of APK size.
public static final String USER_BIRTHDAY_READ = "https://www.googleapis.com/auth/user.birthday.read";
public static final String USER_PHONENUMBERS_READ = "https://www.googleapis.com/auth/user.phonenumbers.read";
public static final String USERINFO_EMAIL = "https://www.googleapis.com/auth/userinfo.email";
public static final String USERINFO_PROFILE = "https://www.googleapis.com/auth/userinfo.profile";
public JSONObject getUserinfo(@NotNull Context context, @NotNull GoogleSignInAccount acct) {
try {
String token = GoogleAuthUtil.getToken(context, acct.getAccount(), "oauth2: " +USERINFO_PROFILE+" "+USER_PHONENUMBERS_READ+" "+USERINFO_EMAIL+" "+USER_BIRTHDAY_READ);
URL url = new URL("https://people.googleapis.com/v1/people/me?"
+"personFields=genders,birthdays,phoneNumbers,emailAddresses"
+"&access_token=" + token);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
int sc = con.getResponseCode();
if (sc == 200) {
InputStream is = con.getInputStream();
JSONObject profile = new JSONObject(readStream(is));
Log.d(TAG, "Got:" + profile.toString(2));
Log.d(TAG, "genders: "+profile.opt("genders"));
Log.d(TAG, "birthdays: "+profile.opt("birthdays"));
Log.d(TAG, "phoneNumbers: "+profile.opt("phoneNumbers"));
return profile;
} else if (sc == 401) {
GoogleAuthUtil.clearToken(context, token);
Log.d("Server auth fejl, prøv igen\n" + readStream(con.getErrorStream()));
} else {
Log.d("Serverfejl: " + sc);
}
} catch (UserRecoverableAuthException recoverableException) {
startActivityForResult(recoverableException.getIntent(), 1234);
} catch (Exception e) {
e.printStackTrace();
}
public static String readStream(InputStream is) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] data = new byte[2048];
int len = 0;
while ((len = is.read(data, 0, data.length)) >= 0) {
bos.write(data, 0, len);
}
is.close();
return new String(bos.toByteArray(), "UTF-8");
}
Output is easily parsable as JSON:
genders: [{"metadata":{"primary":true,"source":{"type":"PROFILE","id":"101628018970026223117"}},"value":"male","formattedValue":"Male"}]
birthdays: [{"metadata":{"primary":true,"source":{"type":"PROFILE","id":"101628018970026223117"}},"date":{"year":1985,"month":3,"day":5}},{"metadata":{"source":{"type":"ACCOUNT","id":"101628018970026223117"}},"date":{"year":1985,"month":3,"day":5}}]