Xamarin.Android - Login With Gmail Authentication

Introduction

Gmail Login is an easy way for users to log in. Gmail Login automatically retrieves all the user information.

Let’s start!

Before starting our Android application creation, we need to create a Gmail Developer account's new application and enable Google API.

Step 1

Go to API Console from https://console.developers.google.com/apis/dashboard. Check the page on the left side corner and go to Project Name Dropdown. Now, click the + button which opens one more window for app creation. It asks for Project Name, followed by clicking "Create" button. Finally, move to dashboard.

 
Step 2

Next, we need to enable API for Google+API. Go to API Library ->Social APIs->Google API. When it is clicked, it enables the API button. Then, click to enable.

 

Step 3

Afterwards, select OAuth then platform for an Android, followed by giving the Name, Package name, Key Hashes [Create Key Link].

 
 
 
Step 4 

Open Visual Studio->New Project->Templates->Visual C#->Android->Blank App. Now, give the Project Name and Project Location.

 

Step 5

Now, go to Solution Explorer-> Project Name-> References. Right-click to "Manage NuGet Packages", followed by opening a new dialog box. This dialog box helps to search Google Plus, followed by installing Xamarin.GooglePlayServices.Plus Packages.

 

Step 6

Go to Solution Explorer-> Project Name-> References, right-click to get more components which opens a new dialog box. This dialog box is required to search the AppCompat, add the Xamarin.Android.Support.v7.AppCompat Library Packages.

 

Step 7

Open Solution Explorer-> Project Name->Resources->layout->Main.axml. Click "Open Design View".

 

AXML code

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">  
  3.     <com.google.android.gms.common.SignInButton android:id="@+id/sign_in_button" android:layout_width="match_parent" android:layout_marginTop="10dp" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginBottom="30dp" android:layout_height="wrap_content" />  
  4.     <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/sign_in_button" android:id="@+id/relativeLayout1" android:layout_marginLeft="20dp">  
  5.         <TextView android:text="Name : " android:textAppearance="?android:attr/textAppearanceMedium" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView1" />  
  6.         <TextView android:textAppearance="?android:attr/textAppearanceMedium" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@+id/textView1" android:id="@+id/TxtName" android:layout_marginLeft="10dp" /> </RelativeLayout>  
  7.     <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/relativeLayout1" android:id="@+id/relativeLayout2" android:layout_marginLeft="20dp" android:layout_marginTop="10dp">  
  8.         <TextView android:text="Gender : " android:textAppearance="?android:attr/textAppearanceMedium" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView2" />  
  9.         <TextView android:textAppearance="?android:attr/textAppearanceMedium" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@+id/textView2" android:id="@+id/TxtGender" />   
  10. </RelativeLayout>  
  11.     <ImageView android:src="@android:drawable/ic_menu_gallery" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/relativeLayout2" android:id="@+id/ImgProfile" android:layout_centerInParent="true" android:layout_marginTop="50dp" />   
  12. </RelativeLayout>  

Step 8

Now, open Solution Explorer-> Project Name->MainActivity.cs. Click Open CS code page view, followed by adding the namespaces given below.

  1. using Android.Gms.Common.Apis;  
  2. using Android.Gms.Common;  
  3. using Android.Gms.Plus;  
  4. using Android.Util;  
  5. using Android.Graphics;  
  6. using System.Net;  

Step 9

Add public class MainActivity: GoogleApiClient.IConnectionCallbacks, GoogleApiClient.IOnConnectionFailedListener Interface.

Step 10

Create new variables followed by assigning all the variables values.

C# code

  1. GoogleApiClient mGoogleApiClient;  
  2. private ConnectionResult mConnectionResult;  
  3. SignInButton mGsignBtn;  
  4. TextView TxtName, TxtGender;  
  5. ImageView ImgProfile;  
  6. private bool mIntentInProgress;  
  7. private bool mSignInClicked;  
  8. private bool mInfoPopulated;  
  9. public string TAG {  
  10.     get;  
  11.     private set;  
  12. }  
  13. protected override void OnCreate(Bundle bundle) {  
  14.     base.OnCreate(bundle);  
  15.     // Set our view from the "main" layout resource  
  16.     SetContentView(Resource.Layout.Main);  
  17.     mGsignBtn = FindViewById < SignInButton > (Resource.Id.sign_in_button);  
  18.     TxtGender = FindViewById < TextView > (Resource.Id.TxtGender);  
  19.     TxtName = FindViewById < TextView > (Resource.Id.TxtName);  
  20.     ImgProfile = FindViewById < ImageView > (Resource.Id.ImgProfile);  
  21.     mGsignBtn.Click += MGsignBtn_Click;  
  22.     GoogleApiClient.Builder builder = new GoogleApiClient.Builder(this);  
  23.     builder.AddConnectionCallbacks(this);  
  24.     builder.AddOnConnectionFailedListener(this);  
  25.     builder.AddApi(PlusClass.API);  
  26.     builder.AddScope(PlusClass.ScopePlusProfile);  
  27.     builder.AddScope(PlusClass.ScopePlusLogin);  
  28.     //Build our IGoogleApiClient  
  29.     mGoogleApiClient = builder.Build();  
  30. }  
  31. protected override void OnStart() {  
  32.     base.OnStart();  
  33.     mGoogleApiClient.Connect();  
  34. }  
  35. protected override void OnStop() {  
  36.     base.OnStop();  
  37.     if (mGoogleApiClient.IsConnected) {  
  38.         mGoogleApiClient.Disconnect();  
  39.     }  
  40. }  
  41. public void OnConnected(Bundle connectionHint) {  
  42.     var person = PlusClass.PeopleApi.GetCurrentPerson(mGoogleApiClient);  
  43.     var name = string.Empty;  
  44.     if (person != null) {  
  45.         TxtName.Text = person.DisplayName;  
  46.         TxtGender.Text = person.Nickname;  
  47.         var Img = person.Image.Url;  
  48.         var imageBitmap = GetImageBitmapFromUrl(Img.Remove(Img.Length - 5));  
  49.         if (imageBitmap != null) ImgProfile.SetImageBitmap(imageBitmap);  
  50.     }  
  51. }  
Google Login Button Events
  1. private void MGsignBtn_Click(object sender, EventArgs e) {  
  2.     if (!mGoogleApiClient.IsConnecting) {  
  3.         mSignInClicked = true;  
  4.         ResolveSignInError();  
  5.     } else if (mGoogleApiClient.IsConnected) {  
  6.         PlusClass.AccountApi.ClearDefaultAccount(mGoogleApiClient);  
  7.         mGoogleApiClient.Disconnect();  
  8.     }  
  9. }  
  10. private void ResolveSignInError() {  
  11.     if (mGoogleApiClient.IsConnecting) {  
  12.         return;  
  13.     }  
  14.     if (mConnectionResult.HasResolution) {  
  15.         try {  
  16.             mIntentInProgress = true;  
  17.             StartIntentSenderForResult(mConnectionResult.Resolution.IntentSender, 0, null, 0, 0, 0);  
  18.         } catch (Android.Content.IntentSender.SendIntentException io) {  
  19.             mIntentInProgress = false;  
  20.             mGoogleApiClient.Connect();  
  21.         }  
  22.     }  
  23. }  
  24. private Bitmap GetImageBitmapFromUrl(String url) {  
  25.     Bitmap imageBitmap = null;  
  26.     try {  
  27.         using(var webClient = new WebClient()) {  
  28.             var imageBytes = webClient.DownloadData(url);  
  29.             if (imageBytes != null && imageBytes.Length > 0) {  
  30.                 imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);  
  31.             }  
  32.         }  
  33.         return imageBitmap;  
  34.     } catch (IOException e) {}  
  35.     return null;  
  36. }  
  37. protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) {  
  38.     base.OnActivityResult(requestCode, resultCode, data);  
  39.     Log.Debug(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);  
  40.     if (requestCode == 0) {  
  41.         if (resultCode != Result.Ok) {  
  42.             mSignInClicked = false;  
  43.         }  
  44.         mIntentInProgress = false;  
  45.         if (!mGoogleApiClient.IsConnecting) {  
  46.             mGoogleApiClient.Connect();  
  47.         }  
  48.     }  
  49. }  

GoogleApiClient.IConnectionCallbacks,GoogleApiClient.IOnConnectionFailedListener Override Methods

  1. public void OnConnectionFailed(ConnectionResult result) {  
  2.     if (!mIntentInProgress) {  
  3.         mConnectionResult = result;  
  4.         if (mSignInClicked) {  
  5.             ResolveSignInError();  
  6.         }  
  7.     }  
  8. }  
  9. public void OnConnectionSuspended(int cause) {}  

Step 11

Finally, we need to give the permissions and Google Key. So, go to Solution Explorer->Project Name->Properties-> AndroidManifest.xml file.

XML code

  1. <uses-permission android:name="android.permission.USE_CREDENTIALS" />  
  2. <uses-permission android:name="android.permission.INTERNET" />  
  3. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.GET_ACCOUNTS" />  
  4. <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />  

Step 12

Press F5 or build and run the application.

 

Finally, we successfully created Xamarin Android app login with Gmail authentication.