Program to implement a Google sign-in in Xamarin
Pre-requisites: Make sure you install Visual Studio 2022 Community Edition or an appropriate version
1. You will need to create a project using Android app (Xamarin) template.
You can use the project name = TestMobileGDrive
2. Using References/Manage Nuget Packages, make sure you include following packages with appropriate version
Xamarin.AndroidX.AppCompat
Xamarin.Essentials
Xamarin.GooglePlayServices.Auth
Make sure your code is as follows
3. filename = activity_main.xml
project folder location = /Resources/layout (create this folder if need be and then add the xml file)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/account_name" />
<Button
android:id="@+id/sign_in_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/sign_in"
android:textColor="@android:color/white"
android:theme="@style/ThemeOverlay.MyDarkButton"
/>
</RelativeLayout>
4. Filename= strings.xml
Folder location: /values
Note: create the file and folder if necessary
Note: The google server client id given below is for example and will not work. Create your own OAuth client id as per the guide on https://developers.google.com/workspace/guides/create-credentials . Once created, replace it in the file within googleserverclientid tag.
<resources>
<string name="app_name">TestMobileGDrive</string>
<string name="action_settings">Settings</string>
<!-- Button labels -->
<string name="sign_in">Sign In</string>
<string name="sign_out">Sign Out</string>
<string name="disconnect">Disconnect</string>
<string name="googleserverclientid">459354647154-d5beleb9ugbvnijq53dh9rf7i56mheta.apps.googleusercontent.com</string>
</resources>
5. Filename = styles.xml
Folder location:/ values
Note: create the file and folder if necessary
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<!-- Dark Buttons -->
<style name="ThemeOverlay.MyDarkButton" parent="ThemeOverlay.AppCompat.Dark">
<item name="colorButtonNormal">@color/blue_grey_500</item>
</style>
</resources>
6. Filename: colors.xml
Folder location: /values
Note: create the file and folder if necessary
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- color name="colorPrimary">#2c3e50</color>
<color name="colorPrimaryDark">#1B3147</color>
<color name="colorAccent">#3498db</color -->
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<color name="launcher_background">#FFFFFF</color>
<color name="blue_grey_500">#607D8B</color>
<color name="blue_grey_600">#546E7A</color>
<color name="blue_grey_700">#455A64</color>
<color name="blue_grey_800">#37474F</color>
<color name="blue_grey_900">#263238</color>
</resources>
7. Filename: MainActivity.cs
Folder location: inside root project folder /
using Android.App;
using Android.Gms.Auth.Api.SignIn;
using Android.Gms.Common;
using Android.OS;
using Android.Runtime;
using Android.Widget;
using AndroidX.AppCompat.App;
using Android.Views;
using Android.Content;
using Android.Gms.Tasks;
using Android.Gms.Common.Apis;
using Android.Content.PM;
namespace TestMobileGDrive
{
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true
, ConfigurationChanges = ConfigChanges.ScreenSize |
ConfigChanges.Orientation |
ConfigChanges.UiMode |
ConfigChanges.ScreenLayout |
ConfigChanges.SmallestScreenSize)
]
public class MainActivity : AppCompatActivity, View.IOnClickListener
{
public GoogleSignInClient mGoogleSignInClient;
const int RC_SIGN_IN = 9001;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
RequestGoogleUserData();
}
public void OnClick(Android.Views.View v)
{
switch (v.Id)
{
case Resource.Id.sign_in_button:
signIn();
break;
// ...
}
}
private void signIn()
{
Intent signInIntent = mGoogleSignInClient.SignInIntent;
StartActivityForResult(signInIntent, RC_SIGN_IN);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN)
{
// The Task returned from this call is always completed, no need to attach
// a listener.
Task task = GoogleSignIn.GetSignedInAccountFromIntent(data);
HandleSignInResult(task);
}
}
protected override void OnStart()
{
base.OnStart();
// Check for existing Google Sign In account, if the user is already signed in
// the GoogleSignInAccount will be non-null.
GoogleSignInAccount account = GoogleSignIn.GetLastSignedInAccount(this);
// Set the dimensions of the Google sign-in button.
/*SignInButton signInButton = (SignInButton)FindViewById(Resource.Id.sign_in_button);
signInButton.SetSize(SignInButton.SizeStandard);
updateUI(account);*/
}
public void updateUI(GoogleSignInAccount account)
{
if (account == null)
{
//account is not signed in. make sign in button visible
FindViewById(Resource.Id.sign_in_button).Visibility = Android.Views.ViewStates.Visible;
}
else {
// account is signed in. make the signin button invisible
FindViewById(Resource.Id.sign_in_button).Visibility = Android.Views.ViewStates.Invisible;
//display account name
TextView accountName = (TextView)FindViewById(Resource.Id.account_name);
accountName.Text = account.Email + "\n Account token=" + account.IdToken;
}
}
public void RequestGoogleUserData()
{
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DefaultSignIn)
.RequestEmail()
.RequestIdToken(Resources.GetString(Resource.String.googleserverclientid))
.Build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.GetClient(this, gso);
FindViewById(Resource.Id.sign_in_button).SetOnClickListener(this);
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void HandleSignInResult(Task completedTask)
{
try
{
ApiException apiEx = new ApiException(Statuses.ResultSuccess);
GoogleSignInAccount account =
(GoogleSignInAccount) completedTask.GetResult(apiEx.Class);
// Signed in successfully, show authenticated UI.
updateUI(account);
}
catch (ApiException e)
{
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
string err = "signInResult:failed code=" + e.StatusCode;
updateUI(null);
}
}
}
}
Comments
Post a Comment