如何在我的Android应用程序中集成谷歌+登录?

时间:2015-11-26 09:05:11

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

大家好我实际上需要从谷歌+通过我的应用程序登录人员我现在阅读google上的文档,其位置是

  

要允许用户登录,请将Google登录集成到您的应用中。初始化GoogleApiClient对象时,请求PLUS_LOGIN和PLUS_ME范围

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

现在我很困惑,我是否应该仅使用上面的代码或首先实施谷歌登录,然后在我的onsuccess方法中编写此代码以从谷歌+获取人物的个人资料。另外在上面的代码Scopes.Scopes.PLUS_LOGIN没有工作,所以我使用PLUS.PLUS_LOGIN谷歌的文档太旧了。

现在我已经使用了上面的代码,但它没有从谷歌+帐户登录,只是它显示了一个对话框,我需要从哪个帐户登录但是当我点击该帐户时它也没有做任何事情目前我正在使用google-sign集成,请参阅下面的代码

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

并且工作很好,但我需要人的性别和他/她的出生日期,这就是为什么我考虑使用谷歌+但问题是谷歌+整合对我不起作用我现在应该做什么 ??

如果有人知道如何使用两个谷歌+或谷歌登录api中的任何一个获取人的性别或出生日期,请告诉我我该怎么做才能真正对我有所帮助。

4 个答案:

答案 0 :(得分:0)

因为您已经说过您当前的应用已经适用于Google登录,所以为了获取Google+个人资料信息,例如性别,生日...,首先,确保您已创建Google+个人资料对于您的Google帐户。然后,您可以使用以下代码更新您的应用。请注意我在.requestScopes(new Scope(Scopes.PLUS_LOGIN))使用GoogleSignInOptions,而不是mGoogleApiClient

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);
            if (person != null){
                    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'

P / S:如果已创建Google+个人资料,但在您的设备中添加Google帐户后,您需要从设备中删除现有的Google帐户,然后重新添加。当您再次运行应用时,系统会显示要求您允许/拒绝访问Google+的消息。当然,您必须单击“允许”。

希望这对您有所帮助,对您来说很清楚!

答案 1 :(得分:0)

我认为这个question就是你所期待的。它清楚地解释了如何获取用户信息。希望这能回答你的问题。

答案 2 :(得分:0)

package com.google_plus;

import android.content.Intent;
import android.content.IntentSender;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;

public class MainActivity extends AppCompatActivity implements  GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{

    private GoogleApiClient mGoogleApiClient;
    private boolean mIntentInProgress;
    private boolean mSignInClicked;
    private ConnectionResult mConnectionResult;
    private static final int RC_SIGN_IN = 0;
    Button google_plus;

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

        mGoogleApiClient =  new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(Plus.API, Plus.PlusOptions.builder().build())
                .addScope(Plus.SCOPE_PLUS_LOGIN)
                .addScope(Plus.SCOPE_PLUS_PROFILE)
                .build();

        google_plus =(Button)findViewById(R.id.login_googleplus);

        google_plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signInWithGplus();
            }
        });


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_SIGN_IN) {
            if (resultCode != RESULT_OK) {
                mSignInClicked = false;
            }
            mIntentInProgress = false;
            if (!mGoogleApiClient.isConnecting()) {
                mGoogleApiClient.connect();
            }
        }

    }

    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    /**
     * Method to resolve any signin errors
     * */
    private void resolveSignInError() {
        if (mConnectionResult.hasResolution()) {
            try {
                mIntentInProgress = true;
                mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
            } catch (IntentSender.SendIntentException e) {
                mIntentInProgress = false;
                mGoogleApiClient.connect();
            }
        }
    }


    @Override
    public void onConnected(Bundle bundle) {
        mSignInClicked = false;
        Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
        // Get user's information
        getProfileInformation();
    }

    @Override
    public void onConnectionSuspended(int i) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        if (!result.hasResolution()) {
            GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
            return;
        }
        if (!mIntentInProgress) {
            mConnectionResult = result;
            if (mSignInClicked) {
                resolveSignInError();
            }
        }
    }

    /**
     * Fetching user's information name, email, profile pic
     * */
    private void getProfileInformation() {
        try {
            if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
                Person currentPerson = Plus.PeopleApi
                        .getCurrentPerson(mGoogleApiClient);
                name = currentPerson.getDisplayName();
                email = Plus.AccountApi.getAccountName(mGoogleApiClient);

                Toast.makeText(MainActivity.this,""+name+ "  ,  "+email,Toast.LENGTH_LONG).show();

            } else {
                signOutFromGplus();
                Toast.makeText(getApplicationContext(), "Sorry we can't reach to your profile please signup with your email here...", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Sign-in into google
     * */
    private void signInWithGplus() {
        if (!mGoogleApiClient.isConnecting()) {
            mSignInClicked = true;
            resolveSignInError();
        }
    }

    private void signOutFromGplus() {
        if (mGoogleApiClient.isConnected()) {
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
            mGoogleApiClient.disconnect();
            mGoogleApiClient.connect();
        }
    }
}


/////////////////// android //////////

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.google_plus">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

    </application>

</manifest>


//////////gradle /////////////////////

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.google_plus"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.google.android.gms:play-services:6.1.71'
}

答案 3 :(得分:0)

This is the code


  public class MainActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener { private static final String TAG = MainActivity.class.getSimpleName(); private static final int RC_SIGN_IN = 007; private GoogleApiClient mGoogleApiClient; private ProgressDialog mProgressDialog; private Button btnSignIn; private Button btnSignOut; private LinearLayout llProfileLayout; private ImageView imgProfilePic; private TextView txtName, txtEmail; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnSignIn = (Button)findViewById(R.id.login); btnSignOut = (Button) findViewById(R.id.logout); imgProfilePic = (ImageView) findViewById(R.id.pic); txtName = (TextView) findViewById(R.id.name); txtEmail = (TextView) findViewById(R.id.email); btnSignIn.setOnClickListener(this); btnSignOut.setOnClickListener(this); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build(); mGoogleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this).addApi(Auth.GOOGLE_SIGN_IN_API, gso).build(); } private void signIn() { Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); } private void signOut() { Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() { @Override public void onResult(Status status) { updateUI(false); } }); } private void revokeAccess() { Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() { @Override public void onResult(Status status) { updateUI(false); } }); } private void handleSignInResult(GoogleSignInResult result) { Log.d(TAG, "handleSignInResult:" + result.isSuccess()); if (result.isSuccess()) { /* Signed in successfully, show authenticated UI.*/ GoogleSignInAccount acct = result.getSignInAccount();
    Log.e(TAG, "display name: " + acct.getDisplayName());

    String personName = acct.getDisplayName();
    String personPhotoUrl = acct.getPhotoUrl().toString();
    String email = acct.getEmail();


    Log.e(TAG, "Name: " + personName + ", email: " + email
            + ", Image: " + personPhotoUrl);

    txtName.setText(personName);
    txtEmail.setText(email);
    ;
} else {

    updateUI(false);
}
}

    @Override
    public void onClick(View v) {
        int id = v.getId();

        switch (id) {
            case R.id.login:
                signIn();
                break;

            case R.id.logout:
                signOut();
                break;

        }
    }

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

                if (requestCode == RC_SIGN_IN) {GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            Log.d(TAG, "onActivityResult: "+result);
            handleSignInResult(result);

        }
    }

    @Override
    public void onStart() {
        super.onStart();

        OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
        if (opr.isDone()) {
        Log.d(TAG, "Got cached sign-in");
            GoogleSignInResult result = opr.get();

        }
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

        Log.d(TAG, "onConnectionFailed:" + connectionResult);
    }



    private void updateUI(boolean isSignedIn) {
        if (isSignedIn) {
            btnSignIn.setVisibility(View.GONE);
            btnSignOut.setVisibility(View.VISIBLE);
            llProfileLayout.setVisibility(View.VISIBLE);
        } else {
            btnSignIn.setVisibility(View.VISIBLE);
            btnSignOut.setVisibility(View.GONE);

        }
    }
}