Android Google Plus integration tutorial

android_gplus.png

In this tutorial, we are going to learn how to integrate Google+ for Android application login and also we will retrieve and display Google+ user profile information. Using the latest version of Google Plus for Android, it takes only a few minutes to add this feature to your app.

By integrating Google Plus in your android app, you can create a simple authentication process where user can directly login to your app using their Google Plus credentials. We can also fetch various user information such as user email, name, profile info etc. Other than authentication process, we can use Google Plus integration for fetching friend list, sharing content from Google Plus and posting purposes also.

Google Sign-In for Android has the following requirements:

  • A compatible Android device that runs Android 2.3 or newer and includes the Google Play Store or an emulator with an AVD that runs the Google APIs platform based on Android 4.2.2 or newer and has Google Play Services version 9.8.0 or newer.
  • The latest version of the Android SDK, including the SDK Tools component. The SDK is available from the Android SDK Manager in Android Studio.
  • A project configured to compile against Android 2.3 (Gingerbread) or newer.
  • The Google Play Services SDK: In Android Studio, select Tools > Android > SDK Manager. Scroll to the bottom of the package list and select Extras > Google Repository. The package is downloaded to your computer and installed in your SDK environment.

Creating a project at Google Developers Console

Before moving ahead to the android project, we have to create a project on Google Developers Console.

Step 1. Log in to Google Plus account and go to this dashboard and click on Create project (top left corner). Step 2. Now fill the details and click on Create. Step 3. Now we need a configuration file for our Android app. So go to this link. Select your app we just created on developer console. And write the package name of your Android studio project. Finally choose country and click on continue. Step 4. In the next screen you will asked for SHA-1. To get SHA-1 Certificate. Open command prompt and navigate to jdk/bin folder. Write the following command and hit enter

# on MAC and any Linux OS
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v

Step 5. Copy the SHA1 and paste it to the Enable Google Services Page. Step 6. Now click on Enable Google Signin. And click on Continue to Generate Configuration Files. Step 7. Now click on Download google-services.json to get your configuration file and save it to app/ directory of your project. Now come to Android studio.

Creating Login activity

Open AndroidManifest.xml file and ddd a uses-permission element to the manifest.

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

Add the dependency to your project-level build.gradle:

classpath 'com.google.gms:google-services:3.0.0'

Add the plugin to your app-level build.gradle:

apply plugin: 'com.google.gms.google-services'
...
dependencies {
    ...
    compile 'com.google.android.gms:play-services-auth:9.0.0'
    compile 'com.google.android.gms:play-services:9.0.0'
}

After that we will make activity for signing in and showing profile info.

Below is activity_main.xml layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <com.google.android.gms.common.SignInButton
        android:id="@+id/btnLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>

    <TextView
        android:id="@+id/tvStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"/>
</LinearLayout>

As you can see I have created a SignInButton button with one TextView (to show name and email).

Now come to MainActivity.java and write the following code.

public class MainActivity extends AppCompatActivity implements View.OnClickListener, 
    GoogleApiClient.OnConnectionFailedListener {
    private SignInButton btnLogin;
    private GoogleSignInOptions gso;
    private GoogleApiClient gac;

    // signin constant to check the activity result
    private int RC_SIGN_IN = 100;

    private TextView tvStatus;

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

        tvStatus = (TextView) findViewById(R.id.tvStatus);

        // initializing google signin option
        gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();

        // initializing SignInButton
        btnLogin = (SignInButton) findViewById(R.id.btnLogin);
        btnLogin.setSize(SignInButton.SIZE_WIDE);

        // initializing GoogleApiClient
        gac = new GoogleApiClient.Builder(MainActivity.this)
                .enableAutoManage(MainActivity.this, this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

        // setting onClick listener to SignInButton
        btnLogin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v == btnLogin) {
            Intent i = Auth.GoogleSignInApi.getSignInIntent(gac);
            startActivityForResult(i, RC_SIGN_IN);
        }
    }

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

    // after the signing we are calling this function
    private void handleSignInResult(GoogleSignInResult result) {
        // if the login succeed
        if (result.isSuccess()) {
            // getting google account
            GoogleSignInAccount acct = result.getSignInAccount();

            // displaying name and email
            tvStatus.setText(String.format("Name: %s\nEMail: %s", acct.getDisplayName(), acct.getEmail()));

            // profile photo
            Log.d("DBG", acct.getPhotoUrl().toString());
        } else {
            Toast.makeText(this, "Login Failed", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.d("DBG", "onConnectionFailed:" + connectionResult);
    }

    @Override
    protected void onStart() {
        super.onStart();
        OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(gac);
        if (opr.isDone()) {
            Log.d(TAG, "Got cached sign-in");
            GoogleSignInResult result = opr.get();
            handleSignInResult(result);
        } else {
            opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
                @Override
                public void onResult(GoogleSignInResult googleSignInResult) {
                    handleSignInResult(googleSignInResult);
                }
            });
        }
    }
}

The class implements GoogleApiClient.OnConnectionFailedListener. We also instantiate an object of GoogleApiClient class. The connect and disconnect method is called on this object in the Activity onStart and onStop methods.

Result

android_gplus_login.png

Creating Share activity

Let's add to activity_main.xml layout Button widget.

<Button
    android:id="@+id/btnShare"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Share"
    android:onClick="share"
    android:visibility="gone"/>

New share() method will make the action

public void share(View v) {
    Intent shareIntent = new PlusShare.Builder(this)
            .setType("text/plain")
            .setText("Hello from Android!")
            .getIntent();
    startActivityForResult(shareIntent, 0);
}

Full code of MainActivity.

public class MainActivity extends AppCompatActivity implements View.OnClickListener, 
    GoogleApiClient.OnConnectionFailedListener {
    private SignInButton btnLogin;
    private GoogleSignInOptions gso;
    private GoogleApiClient gac;
    private Button btnShare;

    // signin constant to check the activity result
    private int RC_SIGN_IN = 100;

    private TextView tvStatus;

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

        tvStatus = (TextView) findViewById(R.id.tvStatus);

        // initializing SignInButton
        btnLogin = (SignInButton) findViewById(R.id.btnLogin);
        btnLogin.setSize(SignInButton.SIZE_WIDE);

        btnShare = (Button) findViewById(R.id.btnShare);

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

        gac = new GoogleApiClient.Builder(MainActivity.this)
                .enableAutoManage(MainActivity.this, this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .addApi(Plus.API)
                .build();

        // setting onClick listener to SignInButton
        btnLogin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v == btnLogin) {
            Intent i = Auth.GoogleSignInApi.getSignInIntent(gac);
            startActivityForResult(i, RC_SIGN_IN);
        }
    }

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

    // after the signing we are calling this function
    private void handleSignInResult(GoogleSignInResult result) {
        // if the login succeed
        if (result.isSuccess()) {
            // getting google account
            GoogleSignInAccount acct = result.getSignInAccount();

            // displaying name and email
            tvStatus.setText(String.format("Name: %s\nEMail: %s", acct.getDisplayName(), acct.getEmail()));
            btnShare.setVisibility(View.VISIBLE);

            // profile photo
            Log.d("DBG", acct.getPhotoUrl().toString());
        } else {
            Toast.makeText(this, "Login Failed", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {}


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

        OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(gac);
        if (opr.isDone()) {
            Log.d("DBG", "Got cached sign-in");
            GoogleSignInResult result = opr.get();
            handleSignInResult(result);
        } else {
            opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
                @Override
                public void onResult(GoogleSignInResult googleSignInResult) {
                    handleSignInResult(googleSignInResult);
                }
            });
        }
    }

    public void share(View v) {
        Intent shareIntent = new PlusShare.Builder(this)
                .setType("text/plain")
                .setText("Hello from Android!")
                .getIntent();
        startActivityForResult(shareIntent, 0);
    }
}

Result

android_gplus_share.png
comments powered by Disqus