How to integrate google+ sign in my android app?

前端 未结 4 1166
天涯浪人
天涯浪人 2021-02-06 15:19

Hello all actually i need to sign in people from google+ through my app now i read documentation on google where it isstated that

To allow users to sign

相关标签:
4条回答
  • 2021-02-06 15:57

    Because you have said your current app works well with Google Sign-in already, so in order to get Google+ profile information such as Gender, Birthday..., first of all, make sure you have created Google+ profile for your Google account. Then you can update your app with the following codes. Please pay attention that I use .requestScopes(new Scope(Scopes.PLUS_LOGIN)) at GoogleSignInOptions, not at mGoogleApiClient.

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

    and

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

    Then

        @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());
                }
            }
        }
    

    Inside build.gradle file

    // 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: if Google+ profile has been created but after the time you add Google account in your device, you need to delete that existing Google account from your device, then re-add. When you run your app again, the message asking you allow/deny to access Google+ will be displayed. And of course, you must click Allow.

    Hope this helps and is clear for you!

    0 讨论(0)
  • 2021-02-06 16:00
    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);
    
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-06 16:03
    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'
    }
    
    0 讨论(0)
  • 2021-02-06 16:08

    I think this question is what you are lookin for.it clearly explains how to get user info. hope this answers your question.

    0 讨论(0)
提交回复
热议问题