获得用户的出生日期&使用Google登录Android的性别

时间:2017-04-05 14:55:09

标签: android google-play-services google-plus google-signin

我已将Google Sign-In集成到我的应用程序中。我可以获得用户EmailDisplayName。现在,我希望获得用户BirthdateGender

我添加了所有必需的requests&amp; Scopes GoogleApiClient // [START configure_signin] // Configure sign-in to request the user's ID, email address, and basic // profile. ID and basic profile are included in DEFAULT_SIGN_IN. GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .requestProfile() <- This .requestScopes( new Scope(Scopes.PLUS_ME), new Scope(Scopes.PROFILE) <- This ) .build(); // [END configure_signin] // [START build_client] // Build a GoogleApiClient with access to the Google Sign-In API and the // options specified by gso. mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this /* FragmentActivity */, new GoogleApiClient.OnConnectionFailedListener() { @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { // An unresolvable error has occurred and Google APIs (including Sign-In) will not // be available. Log.d(TAG, "onConnectionFailed:" + connectionResult); } } /* OnConnectionFailedListener */) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .addScope(new Scope(Scopes.PLUS_ME)) <- This .addScope(new Scope(Scopes.PROFILE)) <- This .build(); // [END build_client] ,所有这些都由API授予。这是代码。

GoogleSignInAccount

以下是private void setupUserData(GoogleSignInAccount acct) { if (acct != null) { mPrefs.setName(acct.getDisplayName()); mPrefs.setEmail(acct.getEmail()); if (acct.getPhotoUrl() != null) { mPrefs.setPicURL(acct.getPhotoUrl().toString()); } Set<Scope> scopes = acct.getGrantedScopes(); <- This for (Scope scope : scopes) { Log.d(TAG, "setupUserData: " + scope.toString()); <- This } } }

中授予的范围
scopes

以下是已授予D/SplashActivity: setupUserData: GrantedScopes size 6 D/SplashActivity: setupUserData: https://www.googleapis.com/auth/plus.me D/SplashActivity: setupUserData: https://www.googleapis.com/auth/userinfo.email D/SplashActivity: setupUserData: https://www.googleapis.com/auth/userinfo.profile D/SplashActivity: setupUserData: email D/SplashActivity: setupUserData: profile D/SplashActivity: setupUserData: openid

的日志
compile 'com.google.android.gms:play-services-auth:10.2.0'
compile 'com.google.android.gms:play-services-plus:10.2.0'

以下是我的Google移动服务的依赖

user's profile information

现在,我不知道如何访问[info] /Users/nnovod/tools/clang+llvm-4.0.0-x86_64-apple-darwin/bin/clang++ [info] -o [info] /Users/nnovod/projects/scalaNative/target/scala-2.11/scalanative-out [info] -lgc [info] -I/usr/local/include [info] -I/Users/nnovod/tools/clang+llvm-4.0.0-x86_64-apple-darwin/include [info] -L/usr/local/lib [info] -L/Users/nnovod/tools/clang+llvm-4.0.0-x86_64-apple-darwin/lib [info] -target [info] x86_64-apple-macosx10.11.0 ... [info] /Users/nnovod/projects/scalaNative/target/scala-2.11/nativelib/wrap.c.o [error] Undefined symbols for architecture x86_64: [error] "_scalanative_alloc", referenced from: [error] _example.Main$::load in example.ll.o [error] _java.io.OutputStream::write_class.ssnr.ByteArray_i32_i32_unit in java.io.ll.o [error] _java.io.OutputStreamWriter::writeImpl_class.java.nio.CharBuffer_unit in java.io.ll.o [error] _java.io.PrintStream::flush_unit in java.io.ll.o [error] _java.io.PrintStream::write_i32_unit in java.io.ll.o [error] _java.io.PrintStream::java$io$PrintStream$$encoder$lzycompute_class.java.io.OutputStreamWriter in java.io.ll.o [error] _java.io.PrintStream::write_class.ssnr.ByteArray_i32_i32_unit in java.io.ll.o [error] ... [error] "_scalanative_init", referenced from: [error] _main in __main.ll.o [error] ld: symbol(s) not found for architecture x86_64 [error] clang-4.0: error: linker command failed with exit code 1 (use -v to see invocation) [info] Compiling LLVM IR to native code (1422 ms) [info] Total (5920 ms) [info] running [info] /Users/nnovod/projects/scalaNative/target/scala-2.11/scalanative-out java.io.IOException: Cannot run program "/Users/nnovod/projects/scalaNative/target/scala-2.11/scalanative-out": error=2, No such file or directory at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048) Caused by: java.io.IOException: error=2, No such file or directory at java.lang.UNIXProcess.forkAndExec(Native Method) at java.lang.UNIXProcess.<init>(UNIXProcess.java:248) at java.lang.ProcessImpl.start(ProcessImpl.java:134) at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029) [trace] Stack trace suppressed: run last *:run for the full output. [error] (*:run) java.io.IOException: Cannot run program "/Users/nnovod/projects/scalaNative/target/scala-2.11/scalanative-out": error=2, No such file or directory [error] Total time: 6 s, completed Apr 5, 2017 10:40:54 AM

7 个答案:

答案 0 :(得分:11)

Getting people and profile information所述,要获取其他个人资料信息和用户的联系人,请使用People API。您必须获得用户的同意才能通过在用户登录时请求其他scopes来访问此信息。

您可以拨打people.get,传递资源名称,以获取每个人的私人联系人和公开个人资料数据。如果您的请求成功,则回复包含Person的实例,其中包括birthdaygender

您可能需要访问我提供的链接以获取更多信息。

答案 1 :(得分:3)

这是完整的工作示例,希望对未来的读者有所帮助。该应用程序首先登录(登录API包括姓名和电子邮件),然后请求生日&amp;性别(People API)身份验证,并将其保存到SharedPreferences以便在下次启动时重复使用。最后,它将打印基本信息和高级(性别和生日)信息。

public class MainActivity extends AppCompatActivity {

    static final private int RC_SIGN_IN = 1;
    static final private String TAG = "hole";
    private WeakReference<MainActivity> weakAct = new WeakReference<>(this);
    private GoogleSignInClient mGoogleSignInClient;
    private GoogleSignInAccount account;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Scope myScope = new Scope("https://www.googleapis.com/auth/user.birthday.read");
        Scope myScope2 = new Scope(Scopes.PLUS_ME);
        Scope myScope3 = new Scope(Scopes.PROFILE); //get name and id
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestScopes(myScope, myScope2)
                .requestEmail()
                .requestProfile()
                .build();

        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        account = GoogleSignIn.getLastSignedInAccount(this);
        if (account == null) {
            reqPerm();
        } else {
            SharedPreferences sharedPref = getSharedPreferences(account.getId(), MODE_PRIVATE);
            if (sharedPref.contains("gender")) {
                printBasic();
                printAdvanced();
            } else {
                new GetProfileDetails(account, weakAct, TAG).execute();
            }
        }
    }

    private void reqPerm() {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    private void printBasic() {
        account = GoogleSignIn.getLastSignedInAccount(this);
        if (account != null) {
            Log.d(TAG, "latest sign in: "
                    + "\n\tPhoto url:" + account.getPhotoUrl()
                    + "\n\tEmail:" + account.getEmail()
                    + "\n\tDisplay name:" + account.getDisplayName()
                    + "\n\tFamily(last) name:" + account.getFamilyName()
                    + "\n\tGiven(first) name:" + account.getGivenName()
                    + "\n\tId:" + account.getId()
                    + "\n\tIdToken:" + account.getIdToken()
            );
        } else {
            Log.w(TAG, "basic info is null");
        }
    }

    private void saveAdvanced(Person meProfile) {
        account = GoogleSignIn.getLastSignedInAccount(this);
        if (account != null) {
            SharedPreferences sharedPref = getSharedPreferences(account.getId(), MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();

            if (n.size() > 0) {
                try {
                    Log.d("hole", "g name: " + n);
                    editor.putString("givenName", n.get(0).getGivenName());
                    editor.putString("familyName", n.get(0).getFamilyName());
                    editor.putString("id", n.get(0).getMetadata().getSource().getId());
                 } catch (Exception e) {
                    e.printStackTrace();
                    //this one should act as fallback priority since it got problem to get name without wait for ~1 minute
                    // ... when create new account will get empty name
                    editor.putString("id", account.getId());
                    editor.putString("givenName", account.getGivenName());
                    editor.putString("familyName", account.getFamilyName());
            }
        }
            List<Gender> genders = meProfile.getGenders();
            if (genders != null && genders.size() > 0) {
                String gender = genders.get(0).getValue();
                Log.d(TAG, "onPostExecute gender: " + gender);
                editor.putString("gender", gender);
            } else {
                Log.d(TAG, "onPostExecute no gender if set to private ");
                editor.putString("gender", ""); //save as main key to know pref saved
            }
            List<Birthday> birthdays = meProfile.getBirthdays();
            if (birthdays != null && birthdays.size() > 0) {
                for (Birthday b : birthdays) { //birthday still able to get even private, unlike gender
                    Date bdate = b.getDate();
                    if (bdate != null) {
                        String bday, bmonth, byear;
                        if (bdate.getDay() != null) bday = bdate.getDay().toString();
                        else bday = "";
                        if (bdate.getMonth() != null) bmonth = bdate.getMonth().toString();
                        else bmonth = "";
                        if (bdate.getYear() != null) byear = bdate.getYear().toString();
                        else byear = "";
                        editor.putString("bday", bday);
                        editor.putString("bmonth", bmonth);
                        editor.putString("byear", byear);
                    }
                }
            } else {
                Log.w(TAG, "saveAdvanced no birthday");
            }
            editor.commit();  //next instruction is print from pref, so don't use apply()
        } else {
            Log.w(TAG, "saveAdvanced no acc");
        }
    }

    private void printAdvanced() {
        account = GoogleSignIn.getLastSignedInAccount(this);
        if (account != null) {
            SharedPreferences sharedPref = getSharedPreferences(account.getId(), MODE_PRIVATE);
            if (sharedPref.contains("gender")) { //this checking works since null still saved
                String gender = sharedPref.getString("gender", "");
                Log.d(TAG, "gender: " + gender);
                if (sharedPref.contains("bday")) { //this checking works since null still saved
                    String bday = sharedPref.getString("bday", "");
                    String bmonth = sharedPref.getString("bmonth", "");
                    String byear = sharedPref.getString("byear", "");
                    Log.d(TAG, bday + "/" + bmonth + "/" + byear);
                } else {
                    Log.w(TAG, "failed ot get birthday from pref");
                }
                String givenName = sharedPref.getString("givenName", "");
                String familyName = sharedPref.getString("familyName", "");
                String id = sharedPref.getString("id", "");
            } else {
                Log.w(TAG, "failed ot get data from pref -2");
            }

        } else {
            Log.w(TAG, "failed ot get data from pref -1");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_SIGN_IN) {
            if (resultCode == Activity.RESULT_OK) {
                Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
                handleSignInResult(task);
            } else {
                Log.w(TAG, "failed, user denied OR no network OR jks SHA1 not configure yet at play console android project");
            }
        }
    }

    private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
        try {
            GoogleSignInAccount account = completedTask.getResult(ApiException.class);
            // Signed in successfully, show authenticated UI.
            new GetProfileDetails(account, weakAct, TAG).execute();
        } catch (ApiException e) { //cancel choose acc will come here with status code 12501 if not check RESULT_OK
            // , more status code at:
            //https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInStatusCodes
            Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
        }
    }

    static class GetProfileDetails extends AsyncTask<Void, Void, Person> {

        private PeopleService ps;
        private int authError = -1;
        private WeakReference<MainActivity> weakAct;
        private String TAG;

        GetProfileDetails(GoogleSignInAccount account, WeakReference<MainActivity> weakAct, String TAG) {
            this.TAG = TAG;
            this.weakAct = weakAct;
            GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(
                    this.weakAct.get(), Collections.singleton(Scopes.PROFILE));
            credential.setSelectedAccount(
                    new Account(account.getEmail(), "com.google"));
            HttpTransport HTTP_TRANSPORT = AndroidHttp.newCompatibleTransport();
            JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
            ps = new PeopleService.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                    .setApplicationName("Google Sign In Quickstart")
                    .build();
        }

        @Override
        protected Person doInBackground(Void... params) {
            Person meProfile = null;
            try {
                meProfile = ps
                        .people()
                        .get("people/me")
                        .setPersonFields("names,genders,birthdays")
                        .execute();
            } catch (UserRecoverableAuthIOException e) {
                e.printStackTrace();
                authError = 0;
            } catch (GoogleJsonResponseException e) {
                e.printStackTrace();
                authError = 1;
            } catch (IOException e) {
                e.printStackTrace();
                authError = 2;
            }
            return meProfile;
        }

        @Override
        protected void onPostExecute(Person meProfile) {
            MainActivity mainAct = weakAct.get();
            if (mainAct != null) {
                mainAct.printBasic();
                if (authError == 0) { //app has been revoke, re-authenticated required.
                    mainAct.reqPerm();
                } else if (authError == 1) {
                    Log.w(TAG, "People API might not enable at" +
                            " https://console.developers.google.com/apis/library/people.googleapis.com/?project=<project name>");
                } else if (authError == 2) {
                    Log.w(TAG, "API io error");
                } else {
                    if (meProfile != null) {
                        mainAct.saveAdvanced(meProfile);
                        mainAct.printAdvanced();
                    }
                }
            }
        }
    }
}

提醒:

  1. 在AndroidManifest.xml中添加<uses-permission android:name="android.permission.INTERNET" />
  2. implementation 'com.google.android.gms:play-services-auth:12.0.1'的{​​{1}}中添加implementation 'com.google.apis:google-api-services-people:v1-rev255-1.23.0'implementation 'com.google.api-client:google-api-client-android:1.23.0'dependencies {}
  3. 在我的情况下,我将build.gradlecompileSdkVersiontargetSdkVersion从27降级到26,因为我在添加#2依赖项后收到警告。
  4. 添加 appcompat-v7signingConfigs { debug { storeFile file('<path to jks file>') keyAlias '<your key alias>' keyPassword '<your key password>' storePassword '<your store password>' } }中,从build.gradle生成的jks文件 - &gt; Build - &gt; Generated Signed APK...
  5. Create new...获取SHA1十六进制密钥,然后访问播放控制台,填写项目名称,应用程序包名称,SHA1十六进制密钥。
  6. https://console.developers.google.com/apis/library/people.googleapis.com/?project= [您的项目ID]“启用People API,项目ID可以从播放控制台获取。请注意,它不是项目名称。
  7. 我注意到库中没有keytool -exportcert -keystore <path to jks file> -list -v,所以我必须对生日端点网址Scopes.BIRTHDAY进行硬编码,链接可以从https://developers.google.com/people/v1/how-tos/authorizing#profile-scopes或“显示范围”中获取在https://developers.google.com/people/api/rest/v1/people/get
  8. 尝试使用API​​“面板
  9. 生日是一个列表,它可能会循环2个日期项目,在我的情况下,一个项目缺少一年。我的代码总是替换以保存这2个项目。可能有更好的方法来处理它。
  10. 性别只有在不私有时才能返回。生日没有这样的限制。
  11. 由于Android设备需要约1分钟的延迟才能获得新创建的帐户名称,因此您可能需要使用PROFILE范围而不是简单的"https://www.googleapis.com/auth/user.birthday.read"account.getGivenName()

答案 2 :(得分:2)

以下是我的回答,希望对您有所帮助。

Plus.PeopleAPI已在Google Play服务9.4中弃用,如Google的声明中所述,请参阅以下使用Google People API的解决方案:

在新的Google登录Play Services 8.3(Isabella Chen的回答)中获取人员详细信息;

虽然明确请求

,但无法通过Google Plus帐户获得私人生日

END OF UPDATE

首先,请确保您已为自己的Google帐户创建了Google+个人资料。然后您可以参考以下代码:

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)             
            .requestScopes(new Scope(Scopes.PLUS_LOGIN))
            .requestEmail()
            .build();

mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .addApi(Plus.API)
            .build();

然后

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        handleSignInResult(result);

        // G+
        Person person  = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
        Log.e(TAG, "--------------------------------");
        Log.e(TAG, "Display Name: " + person.getDisplayName());
        Log.e(TAG, "Gender: " + person.getGender());
        Log.e(TAG, "AboutMe: " + person.getAboutMe());
        Log.e(TAG, "Birthday: " + person.getBirthday());
        Log.e(TAG, "Current Location: " + person.getCurrentLocation());
        Log.e(TAG, "Language: " + person.getLanguage());
    }
}

内部build.gradle文件

// Google登录的依赖关系

   compile 'com.google.android.gms:play-services-auth:8.3.0'
   compile 'com.google.android.gms:play-services-plus:8.3.0'

您可以查看belo GitHub示例项目。希望这有助于解决您的问题。

https://github.com/ngocchung/GoogleSignInDemo

如果您想要最新的集成,请点击以下链接,其中包含一个很好的文档以及有关代码的简要说明,它是所有参数。

https://developers.google.com/identity/sign-in/android/start-integrating

GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(getActivity());
if (acct != null) {
  String personName = acct.getDisplayName();
  String personGivenName = acct.getGivenName();
  String personFamilyName = acct.getFamilyName();
  String personEmail = acct.getEmail();
  String personId = acct.getId();
  Uri personPhoto = acct.getPhotoUrl();
}

答案 3 :(得分:2)

Gradle

implementation "com.google.android.gms:play-services-auth:${google_play_service_version}"
implementation 'com.google.apis:google-api-services-people:v1-rev354-1.25.0'
implementation ('com.google.api-client:google-api-client-android:1.23.0') {
    exclude group: 'org.apache.httpcomponents'
}

身份验证

private void setupGoogleLogin() {
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestScopes(new Scope(PeopleApi.CONTACT_SCOPE), new Scope(PeopleApi.BIRTHDAY_SCOPE))
                .requestEmail()
                .build();

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, mOnConnectionFailedListener)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();
    }

PeopleApi

public class PeopleApi {
    public static final String CONTACT_SCOPE = "https://www.googleapis.com/auth/contacts.readonly";
    public static final String BIRTHDAY_SCOPE = "https://www.googleapis.com/auth/user.birthday.read";
    private static PeopleService mInstance;

    private static PeopleService getService() {
        if (mInstance == null) mInstance = initializeService();
        return mInstance;
    }

    private static PeopleService initializeService() {
        Context context = BHApp.getContext();
        GoogleAccountCredential credential =
                GoogleAccountCredential.usingOAuth2(context, Arrays.asList(CONTACT_SCOPE, BIRTHDAY_SCOPE));
        credential.setSelectedAccount(GoogleSignIn.getLastSignedInAccount(context).getAccount());

        return new PeopleService.Builder(AndroidHttp.newCompatibleTransport(), JacksonFactory.getDefaultInstance(), credential)
                .setApplicationName(context.getString(R.string.app_name)).build();
    }

    public static Person getProfile() {
        try {
            return getService().people().get("people/me")
                    .setPersonFields("genders,birthdays,addresses")
                    .execute();
        } catch (Exception e) {
            Utils.handleException(e);
            return null;
        }
    }

    public static String getBirthday(Person person) {
        try {
            List<Birthday> birthdayList = person.getBirthdays();
            if (birthdayList == null) return Utils.EMPTY_STRING;
            Date date = null;
            for (Birthday birthday : birthdayList) {
                date = birthday.getDate();
                if (date != null && date.size() >= 3) break;
                else date = null;
            }
            if (date == null) return Utils.EMPTY_STRING;
            Calendar calendar = Calendar.getInstance();
            calendar.set(date.getYear(), date.getMonth() - 1, date.getDay());
            return Utils.convertDateToString(calendar);
        } catch (Exception e) {
            Utils.handleException(e);
            return Utils.EMPTY_STRING;
        }
    }

    private static final String CITY_SUFFIX = " city";
    public static android.location.Address getLocation(Person person) {
        try {
            List<Address> addressList = person.getAddresses();
            if (addressList == null) return null;
            String city = null;
            for (Address add : addressList) {
                city = add.getCity();
                if (!TextUtils.isEmpty(city)) break;
            }
            if (TextUtils.isEmpty(city)) return null;

            Geocoder geocoder = new Geocoder(BHApp.getContext());

            List<android.location.Address> addresses =  geocoder.getFromLocationName(city + CITY_SUFFIX, 1);
            if (addresses == null || addresses.isEmpty()) return null;
            return addresses.get(0);
        } catch (Exception e) {
            Utils.handleException(e);
            return null;
        }
    }

    public static String getGender(Person person) {
        List<Gender> genders = person.getGenders();
        if (genders == null || genders.isEmpty()) return null;
        Gender gender = genders.get(0);
        return String.valueOf(Enum.Gender.getEnumByValue(gender.getValue()).getId());
    }
}

我希望它会有所帮助:)

答案 4 :(得分:0)

build.gradle依赖项

中添加此内容
implementation 'com.google.android.gms:play-services-auth:11.8.0'

试试这个

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.plus.People;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;

public class MainActivity extends AppCompatActivity implements  GoogleApiClient.OnConnectionFailedListener{

private SignInButton signInButton;
private GoogleSignInOptions gso;
private GoogleApiClient mGoogleApiClient;
private int SIGN_IN = 30;

@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();
    signInButton = (SignInButton) findViewById(R.id.sign_in_button);
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .addApi(Plus.API)
            .build();

signInButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
            startActivityForResult(signInIntent, SIGN_IN);
        }
    });
}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    //If signin
    if (requestCode == SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        //Calling a new function to handle signin
        handleSignInResult(result);
    }
}

private void handleSignInResult(GoogleSignInResult result) {

    if (result.isSuccess()) {

        final GoogleSignInAccount acct = result.getSignInAccount();


        String name = acct.getDisplayName();
        final String mail = acct.getEmail();
        // String photourl = acct.getPhotoUrl().toString();

        final String givenname="",familyname="",displayname="",birthday="";

        Plus.PeopleApi.load(mGoogleApiClient, acct.getId()).setResultCallback(new ResultCallback<People.LoadPeopleResult>() {
            @Override
            public void onResult(@NonNull People.LoadPeopleResult loadPeopleResult) {
                Person person = loadPeopleResult.getPersonBuffer().get(0);

                Log.d("GivenName ", person.getName().getGivenName());
                Log.d("FamilyName ",person.getName().getFamilyName());
                Log.d("DisplayName ",person.getDisplayName());
                Log.d("gender ", String.valueOf(person.getGender())); //0 = male 1 = female
                String gender="";
                if(person.getGender() == 0){
                    gender = "Male";
                }else {
                    gender = "Female";
                }
                    Log.d("Gender ",gender);
                if(person.hasBirthday()){
                    Log.d("Birthday ",person.getBirthday());
                }


            }
        });
    } else {

        Toast.makeText(this, "Login Failed", Toast.LENGTH_LONG).show();
    }
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}
}

答案 5 :(得分:0)

使用People api,您可以检索生日和性别详细信息。

使用依赖关系&com.google.apis:google-api-services-people:v1-rev4-1.22.0&#39;在gradle中包括人们的api。

public void fetchProfileDetails() {
    GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(context, Collections.singleton(Scopes.PROFILE));
    credential.setSelectedAccount(
            new Account(gsr.getSignInAccount().getEmail(), "com.google"));
    /** Global instance of the HTTP transport. */
    HttpTransport HTTP_TRANSPORT = AndroidHttp.newCompatibleTransport();
    /** Global instance of the JSON factory. */
    JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

    People service = new People.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
            .setApplicationName("AppName")
            .build();
    try {
        meProfile = service.people().get("people/me").execute();
        List<Gender> genders = meProfile.getGenders();
        if (genders != null && genders.size() > 0) {
            String gender = genders.get(0).getValue();
        }
        List<Birthday> birthdays = meProfile.getBirthdays();
        if (birthdays != null && birthdays.size() > 0) {
            String birthday = birthdays.get(0).getText();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

答案 6 :(得分:0)

//Global instance of the HTTP transport.
private val HTTP_TRANSPORT: HttpTransport = AndroidHttp.newCompatibleTransport()

//Global instance of the JSON factory.
private val JSON_FACTORY: JsonFactory = JacksonFactory.getDefaultInstance()

Thread {
        var meProfile: Person? = null
        try {
            val googleAccountCredential: GoogleAccountCredential = GoogleAccountCredential.usingOAuth2(
                context, Collections.singleton(Scopes.PROFILE)
            )
            googleAccountCredential.selectedAccount = Account(googleSignInAccount.email, "com.google")
            val service: People = People.Builder(HTTP_TRANSPORT, JSON_FACTORY, googleAccountCredential)
                .setApplicationName("Google Sign In Quickstart")
                .build()

            meProfile = service
                .people()
                .get("people/me")
                .set("personFields", "genders")
                .execute()
        } catch (e: UserRecoverableAuthIOException) {
            e.printStackTrace()
        } catch (e: GoogleJsonResponseException) {
            e.printStackTrace()
        } catch (e: IOException ) {
            e.printStackTrace()
        }

        if (meProfile != null && !meProfile.genders.isNullOrEmpty()) {
            Log.d(TAG, "Gender: ${meProfile.genders[0]["value"]}")
        } else {
            Log.d(TAG, "Gender only able to return if it's not private.")
        }

    }.start()

重要提示:

  • googleSignInAccount是要获取性别的帐户。
  • 在Google个人资料的版本中,该类型的隐私必须是公开的,以便可以获取数据。

GL

来源

相关问题