首页 文章

如何在Android中使用Google登录获取性别等 Profiles ?

提问于
浏览
24

我想将谷歌登录集成到我的应用程序,当用户首次登录我将创建一个帐户绑定到此,所以我需要一些配置文件,如性别,区域设置等,我尝试作为谷歌登录文档和快速-start示例显示:

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();

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

点击登录时我会打电话:

Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, RC_SIGN_IN);

登录成功后,我可以在onActivityResult中获取数据结构GoogleSignInResult,来自GoogleSignInResult我可以获得一个GoogleSignInAccount,其中只包含DisplayName,email和id . 但是在https://developers.google.com/apis-explorer/#p/中,我可以获得性别,区域设置等 Profiles . 我错过了什么吗?

我试过google plus api,似乎我可以得到我想要的东西 . 但是不知道如何使用,doc说创建客户端是这样的:

mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(Plus.API)
            .addScope(new Scope(Scopes.PLUS_LOGIN))
            .addScope(new Scope(Scopes.PLUS_ME))
            .build();

但是当我使用它时,单击登录按钮将导致应用程序崩溃 .

Update: 更新到新版Google的问题登录Missing api_key/current key with Google Services 3.0.0

4 回答

  • 30

    更新:

    由于 Plus.PeopleApi 已在Google Play服务9.4中弃用为Google's declaration notes,因此请使用Google People API参考以下解决方案:

    在新的Google登录Play Services 8.3中获取人员详细信息(Isabella Chen的回答);虽然明确要求,但无法通过Google Plus帐户获得私人生日

    更新结束


    首先,请确保您已为自己的Google帐户创建了Google Profiles . 然后您可以参考以下代码:

    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.i(TAG, "--------------------------------");
                Log.i(TAG, "Display Name: " + person.getDisplayName());
                Log.i(TAG, "Gender: " + person.getGender());
                Log.i(TAG, "AboutMe: " + person.getAboutMe());
                Log.i(TAG, "Birthday: " + person.getBirthday());
                Log.i(TAG, "Current Location: " + person.getCurrentLocation());
                Log.i(TAG, "Language: " + person.getLanguage());
            }
        }
    

    build.gradle 文件中

    // Dependency for Google Sign-In
    compile 'com.google.android.gms:play-services-auth:8.3.0'
    compile 'com.google.android.gms:play-services-plus:8.3.0'
    

    你可以看一下My GitHub sample project . 希望这可以帮助!

  • 3

    Plus人员的东西已被弃用,不再使用它了 . 执行此操作的方法是使用Google People API在项目中启用此API . 如果不这样做,Studio中抛出的异常包含一个直接指向项目的链接以启用它(很好) .

    在应用程序的build.gradle中包含以下依赖项:

    compile 'com.google.api-client:google-api-client:1.22.0'
    compile 'com.google.api-client:google-api-client-android:1.22.0'
    compile 'com.google.apis:google-api-services-people:v1-rev4-1.22.0'
    

    像正常一样授权GoogleSignIn . 它不需要除基本帐户之外的任何范围或Api,例如

    GoogleSignInOptions.DEFAULT_SIGN_IN
    
    .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
    

    您只需要电子邮件和 Profiles .

    现在,一旦您获得了成功的登录结果,您就可以获得该帐户,包括电子邮件(也可以使用该ID进行此操作) .

    final GoogleSignInAccount acct = googleSignInResult.getSignInAccount();
    

    现在新的部分:创建并执行AsyncTask以在收到acct电子邮件后调用Google People API .

    // get Cover Photo Asynchronously
    new GetCoverPhotoAsyncTask().execute(Prefs.getPersonEmail());
    

    这是AsyncTask:

    // Retrieve and save the url to the users Cover photo if they have one
    private class GetCoverPhotoAsyncTask extends AsyncTask<String, Void, Void> {
        HttpTransport httpTransport = new NetHttpTransport();
        JacksonFactory jsonFactory = new JacksonFactory();
    
        // Retrieved from the sigin result of an authorized GoogleSignIn
        String personEmail;
    
        @Override
        protected Void doInBackground(String... params) {
            personEmail = params[0];
            Person userProfile = null;
            Collection<String> scopes = new ArrayList<>(Collections.singletonList(Scopes.PROFILE));
    
            GoogleAccountCredential credential =
                    GoogleAccountCredential.usingOAuth2(SignInActivity.this, scopes);
            credential.setSelectedAccount(new Account(personEmail, "com.google"));
    
            People service = new People.Builder(httpTransport, jsonFactory, credential)
                    .setApplicationName(getString(R.string.app_name)) // your app name
                    .build();
    
            // Get info. on user
            try {
                userProfile = service.people().get("people/me").execute();
            } catch (IOException e) {
                Log.e(TAG, e.getMessage(), e);
            }
    
            // Get whatever you want
            if (userProfile != null) {
                List<CoverPhoto> covers = userProfile.getCoverPhotos();
                if (covers != null && covers.size() > 0) {
                    CoverPhoto cover = covers.get(0);
                    if (cover != null) {
                        // save url to cover photo here, load at will
                        //Prefs.setPersonCoverPhoto(cover.getUrl());
                    }
                }
            }
    
            return null;
        }
    }
    

    这是Person提供的东西

    如果将代码粘贴到项目中,请确保正确解析导入 . 与一些较旧的API有重叠的类名 .

  • 7

    登录后,执行:

    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);
    
                LogUtil.d("googleuser: getGivenName " + (person.getName().getGivenName()));
                LogUtil.d("googleuser: getFamilyName " + (person.getName().getFamilyName()));
                LogUtil.d("googleuser: getDisplayName " + (person.getDisplayName()));
                LogUtil.d("googleuser: getGender " + (person.getGender() + ""));
                LogUtil.d("googleuser: getBirthday " + (person.getBirthday() + ""));
            }
        });
    
  • 2

    创建如下所示的google登录选项 . 这对我来说很完美

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

相关问题