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 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 :
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <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" /> <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"> <TextView android:text="Name : " android:textAppearance="?android:attr/textAppearanceMedium" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView1" /> <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> <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"> <TextView android:text="Gender : " android:textAppearance="?android:attr/textAppearanceMedium" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView2" /> <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" /> </RelativeLayout> <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" /> </RelativeLayout>
Step 8 : Now, open Solution Explorer-> Project Name->MainActivity.cs. Click Open CS code page view, followed by adding the namespaces given below.
using Android.Gms.Common.Apis; using Android.Gms.Common; using Android.Gms.Plus; using Android.Util; using Android.Graphics; 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 :
GoogleApiClient mGoogleApiClient; private ConnectionResult mConnectionResult; SignInButton mGsignBtn; TextView TxtName, TxtGender; ImageView ImgProfile; private bool mIntentInProgress; private bool mSignInClicked; private bool mInfoPopulated; public string TAG { get; private set; } protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); mGsignBtn = FindViewById<SignInButton>(Resource.Id.sign_in_button); TxtGender = FindViewById<TextView>(Resource.Id.TxtGender); TxtName = FindViewById<TextView>(Resource.Id.TxtName); ImgProfile = FindViewById<ImageView>(Resource.Id.ImgProfile); mGsignBtn.Click += MGsignBtn_Click; GoogleApiClient.Builder builder = new GoogleApiClient.Builder(this); builder.AddConnectionCallbacks(this); builder.AddOnConnectionFailedListener(this); builder.AddApi(PlusClass.API); builder.AddScope(PlusClass.ScopePlusProfile); builder.AddScope(PlusClass.ScopePlusLogin); //Build our IGoogleApiClient mGoogleApiClient = builder.Build(); } protected override void OnStart() { base.OnStart(); mGoogleApiClient.Connect(); } protected override void OnStop() { base.OnStop(); if (mGoogleApiClient.IsConnected) { mGoogleApiClient.Disconnect(); } } public void OnConnected(Bundle connectionHint) { var person = PlusClass.PeopleApi.GetCurrentPerson(mGoogleApiClient); var name = string.Empty; if (person != null) { TxtName.Text = person.DisplayName; TxtGender.Text= person.Nickname; var Img = person.Image.Url; var imageBitmap = GetImageBitmapFromUrl(Img.Remove(Img.Length-5)); if(imageBitmap!=null) ImgProfile.SetImageBitmap(imageBitmap); } }
Google Login Button Events :
private void MGsignBtn_Click(object sender, EventArgs e) { if (!mGoogleApiClient.IsConnecting) { mSignInClicked = true; ResolveSignInError(); } else if (mGoogleApiClient.IsConnected) { PlusClass.AccountApi.ClearDefaultAccount(mGoogleApiClient); mGoogleApiClient.Disconnect(); } } private void ResolveSignInError() { if (mGoogleApiClient.IsConnecting) { return; } if (mConnectionResult.HasResolution) { try { mIntentInProgress = true; StartIntentSenderForResult(mConnectionResult.Resolution.IntentSender, 0, null, 0, 0, 0); } catch (Android.Content.IntentSender.SendIntentException io) { mIntentInProgress = false; mGoogleApiClient.Connect(); } } } private Bitmap GetImageBitmapFromUrl(String url) { Bitmap imageBitmap = null; try { using(var webClient = new WebClient()) { var imageBytes = webClient.DownloadData(url); if (imageBytes != null && imageBytes.Length > 0) { imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length); } } return imageBitmap; } catch (IOException e) {} return null; } protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); Log.Debug(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data); if (requestCode == 0) { if (resultCode != Result.Ok) { mSignInClicked = false; } mIntentInProgress = false; if (!mGoogleApiClient.IsConnecting) { mGoogleApiClient.Connect(); } } }
GoogleApiClient.IConnectionCallbacks,GoogleApiClient.IOnConnectionFailedListener Override Methods :
public void OnConnectionFailed(ConnectionResult result) { if (!mIntentInProgress) { mConnectionResult = result; if (mSignInClicked) { ResolveSignInError(); } } } 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.
<uses-permission android:name="android.permission.USE_CREDENTIALS" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.GET_ACCOUNTS" /> <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.
Download Source Here..
Finally, we successfully created Xamarin Android app login with Gmail authentication.
Anbu Mani(Microsoft MVP) is working Software Engineer in Changepond Technologies, Chennai, Tamilnadu, India. Having 4+ years of experience and his area of interest is C#, ASP.NET, SQL Server, Xamarin and Xamarin Forms,Azure…etc