All CategoriesAndroid App Development

How to Integrate Google Plus in Android

Android gives us the functionalities to integrate Google Plus in our application by following some simple steps. It is quite easy to implement in our application and show the user details by Sign In.
Here we will connect with Google Plus and show user details like name, email, profile pic etc. We can also get the other details once we sign in successfully like a  list of circles, share post, friends list etc.
Google Plus
gives us the advantage of getting user details so, we can get more users details by the registration process and use the profile information easily in our application if there is a need.
Before implementing Google Plus firstly, we will have to check SDK manager that whether the Google play services in installed or not. If not, then install it and update it to the latest version.
We have to generate the google-services.json file for creating this simple application.
So, let’s see the steps for it:

Register the Application and Generate google-services.json file:

We have to create the new project on Google developer console and after follow all the details we generate google-services.json file and use it in our application in Android Studio.
1. Create an Application GooglePlusExampleAndroid in Android Studio.
2. Go to Google Developer Console and after selecting Android give the project name and package name. Use the same package name as we used in our application in Android studio.
 

 
3. After this press ‘Continue’ to Choose and configure services. Here it will ask for SHA-1 fingerprint. So, we have to generate the SHA-1 fingerprint using Java key tool.
4. Open your terminal and execute the below command for generating SHA-1 fingerprint on Windows.Command: keytool -list -v -keystore “%USERPROFILE%\.android\debug.keystore” -alias androiddebugkey -storepass android -keypass androidNow, if we see on terminal there is a SHA-1 fingerprint. So use this fingerprint on Google developers console like this.

 
5. Press Enable Google Sign In and after press generate Configuration file
 

 
6. Now, the next screen appears for google-services.json file.
7. Simply Download this file and copy this file to your app directory. This file includes configuration details, keys, and identifiers.Now, we have done all on Google developers console just continue with the app.

Add the Dependencies:

Here we add the dependencies for project level and app level build.gradle file.
project level build.gradle file:

Add this

dependencies {
    classpath 'com.google.gms:google-services:3.0.0'
    }

app level build.gradle file:

Add the dependency

dependencies {
    compile 'com.google.android.gms:play-services-auth:9.2.1'
    compile "com.squareup.picasso:picasso:2.4.0"
}
apply plugin: 'com.google.gms.google-services'

Here, we add the Picasso library for getting the profile picture.

AndroidManifest.xml:

Here, we add the permission for the internet.

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

Example with Code:  Here in this example, we are going to create an application which shows the user’s profile pic, its name, email, and other options we have discussed above.
activity_main.xml: This is our main layout file here we create the Google + Sign In button, Logout button, 2 TextView’s one for username and another for email and an ImageView for profile pic

Add the code here

<LinearLayout
    android:id="@+id/ll_Profile"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="20dp"
    android:orientation="horizontal"
    android:weightSum="3"
    android:visibility="gone">
    <ImageView
        android:id="@+id/iv_ProfilePic"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:orientation="vertical"
        android:layout_weight="2" >
        <TextView
            android:id="@+id/tv_Name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:textSize="20dp" />
        <TextView
            android:id="@+id/tv_Email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:textSize="18dp" />
    </LinearLayout>
</LinearLayout>
<com.google.android.gms.common.SignInButton
    android:id="@+id/btn_sign_in"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="20dp"/>
<Button
    android:id="@+id/btn_sign_out"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/btn_logout_from_google"
    android:visibility="gone"
    android:layout_marginBottom="10dp"
    android:background="@color/colorPrimary"
    android:textColor="#ffffff"/>

Now, implement all the properties of these widgets in our main activity.

MainActivity.java:

This is our MainActivity which implements GoogleApiClient.OnConnectionFailedListener.
Here, we take the reference of all widgets and integrate other properties.

Initialize:

private static final int RC_SIGN_IN = 007;
private GoogleApiClient mGoogleApiClient;
private ProgressDialog mProgressDialog;
private SignInButton btn_SignIN;
private Button btn_SignOut;
private LinearLayout ll_profileLayout;
private ImageView iv_profilePic;
private TextView tv_Name, tv_Email;

Add the code in onCreate(){..}:

Take the reference of all widgets and set the listeners on buttons.

btn_SignIN = (SignInButton) findViewById(R.id.btn_sign_in);
btn_SignOut = (Button) findViewById(R.id.btn_sign_out);
ll_profileLayout = (LinearLayout) findViewById(R.id.ll_Profile);
iv_profilePic = (ImageView) findViewById(R.id.iv_ProfilePic);
tv_Name = (TextView) findViewById(R.id.tv_Name);
tv_Email = (TextView) findViewById(R.id.tv_Email);
btn_SignIN.setOnClickListener(this);
btn_SignOut.setOnClickListener(this);

 
Now, set the properties for Customizing Google + sign in button.

btn_SignIN.setSize(SignInButton.SIZE_STANDARD);
btn_SignIN.setScopes(gso.getScopeArray());

Then we will create the instance of GoogleApiClient in this method add the code for 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();

Add the code for Sign In

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

Add the code for Sign Out

Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
        new ResultCallback<Status>() {
            @Override
            public void onResult(Status status) {
                updateUI(false);
            }
        });

Here, we will create a method handleSignInResult(..) which shows the authenticated UI when users login successfully.

Add the code in this method.

private void handleSignInResult(GoogleSignInResult result) {
    Log.d(TAG, "handleSignInResult:" + result.isSuccess());
    if (result.isSuccess()) {
        GoogleSignInAccount acct = result.getSignInAccount();
        Log.e(TAG, "display name: " + acct.getDisplayName());
        String user_Name = acct.getDisplayName();
        String user_profilePic = acct.getPhotoUrl().toString();
        String user_Email = acct.getEmail();
        Log.e(TAG, "Name: " + user_Name + ", user_Email: " + user_Email
                + ", Image: " + user_profilePic);
        tv_Name.setText(user_Name);
        tv_Email.setText(user_Email);
        Picasso.with(getApplicationContext()).load(user_profilePic).into(iv_profilePic);
        updateUI(true);
    } else {
        updateUI(false);
    }
}

Picasso is used to fetch the user’s profile pic.
Also, we will add some properties in onStart() method for checking the cache Google Sign In.
Add the code in this method.

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

Here in this activity, updateUI() method is used to hide and show the buttons accordingly when the user signs in or signs out and update the UI.

Output:

 


Download Source Code: GitHub

Conclusion:

This is a simple example of how to integrate Google Plus into Android application. Here, we see there are some steps like generating the google-services.json file which is used for creating this and Google play services API which is important for integrating Google application. By using all of this we will easily Sign in and get the profile information of the user in our application. So, this is all about Google Plus it is very important and popular in Android development .
Keep visiting www.acadgild.com for more updates on the technical and certification courses.

One Comment

  1. Pingback: AppReview.ir - ورود در اپلیکیشن اندروید از طریق گوگل پلاس

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Close