User Session Management In Xamarin Forms

Rohit Kelkar
Globant
Published in
3 min readJan 6, 2022

Hello readers, especially the mobile app developers who are here to get some help and reference about how we can manage user sessions inside our Xamarin forms application.

Jumping straight to the topic, we all have faced this at some point in our development process about having the requirement to handle user sessions, detect user inactivity for a specific amount of time and perform some actions on it. A typical scenario includes logging the user out of the app to the login screen after “N” minutes of inactivity.

From the user's perspective, inactivity for the app includes that the user has not interacted, touched, scrolled, tapped, or done any kind of activity with our application. For such scenarios, we need to handle Auto Logout and redirect the user to a Login screen (Depending on business requirement).

In Xamarin Forms Applications, there is no such inbuilt provision and we need to build it per business requirement. So let us divide this task into two parts.

Part 1 : Create session manager and add methods to start, stop and extend a session.
Part 2 : Detect user interaction with the App for Android and iOS and interact with session manager to manage session.

Let’s start some coding here with Part 1.
Here we create the AppSessionManager.cs as singleton a class.

using System;
using System.Diagnostics;
using Xamarin.Forms;
namespace SessionManager
{
public sealed class AppSessionManager
{
private static readonly Lazy<AppSessionManager> lazy = new Lazy<AppSessionManager>();
public static AppSessionManager Instance { get { return lazy.Value; } }
private Stopwatch StopWatch = new Stopwatch();
private readonly int _sessionThreasholdMinutes = 1;
public AppSessionManager()
{
SessionDuration = TimeSpan.FromMinutes(_sessionThreasholdMinutes);
}
private TimeSpan SessionDuration;public void EndSession()
{
if (StopWatch.IsRunning)
{
StopWatch.Stop();
}
}
public void ExtendSession()
{
if (StopWatch.IsRunning)
{
StopWatch.Restart();
}
}
public void StartSession()
{
if (!StopWatch.IsRunning)
{
StopWatch.Restart();
}
Console.WriteLine("Session Started at " + DateTime.Now.ToLongTimeString());
Device.StartTimer(new TimeSpan(0, 0, 1), () =>
{
bool isTimerRunning = true;
if (StopWatch.IsRunning && StopWatch.Elapsed.Minutes >= SessionDuration.Minutes) //User was inactive for N minutes
{
RedirectAndInformInactivity();
EndSession();
isTimerRunning = false;
}
Console.WriteLine("Current Time Elapsed -" + StopWatch.Elapsed.ToString());
return isTimerRunning;
});
}//TODOprivate void RedirectAndInformInactivity()
{
Device.BeginInvokeOnMainThread(() =>
{
Application.Current.MainPage.DisplayAlert("Session Expired", "Your session has expired", "Restart");
});
}
}
}

In the above class, we specify the number of minutes for which the inactivity needs to be detected. You can make it property as well if needed to define the dynamic time limit for inactivity within the app lifecycle. It has methods to Start, Stop and Extend the current session which would be used by the app.

The session needs to be started when the App Launches or depending upon the business requirement. The below line when added starts the new session.

AppSessionManager.Instance.StartSession();

So Xamarin Android and Xamarin iOS both provide different ways to implement this and detect user interaction with the app.

Xamarin Android Implementation :

Android project provides a simple implementation. Override the below method inside MainActitivity.cs in Android project.
This method gets invoked when user interacts with the app and calls the ExtendSession method of AppSessionManager to restart the timer as shown in above implementation.

public override void OnUserInteraction()
{
base.OnUserInteraction();
AppSessionManager.Instance.ExtendSession();
Console.WriteLine("Touch detected. Extending user session");
}

Xamarin iOS Implementation :

On iOS, we need to create a custom UIApplication class that inherits the UIApplication as shown below and modify the Main.cs file to use the custom UIApplication class.

  1. Create CustomUIApplication class( You can name it the way you want)
using System;
using System.Linq;
using UIKit;
namespace SessionManager.iOS
{
public class SessionManagerApp : UIApplication
{
public SessionManagerApp() : base()
{
}
public SessionManagerApp(IntPtr handle) : base(handle)
{
}
public SessionManagerApp(Foundation.NSObjectFlag t) : base(t)
{
}
public override void SendEvent(UIEvent uievent)
{
if (uievent.Type == UIEventType.Touches)
{
if (uievent.AllTouches.Cast<UITouch>().Any(t => t.Phase == UITouchPhase.Began))
{
AppSessionManager.Instance.ExtendSession();
Console.WriteLine("Touch detected. Extending user session");
}
}
base.SendEvent(uievent);
}
}
}

2. Modify Main.cs and add the below code.

public class Application
{
static void Main(string[] args)
{
UIApplication.Main(args, typeof(SessionManagerApp), typeof(AppDelegate));
}
}

You’re all set !! Now you have the functions in your android and iOS projects which detect the user interaction and use AppSessionManager to extend the session to the next “N” minutes.

You need to put the logic inside AppSessionManager.cs to redirect the user to the required page when the session expires (Check the TODO).

You can check the Git repository for this project here https://github.globant.com/Rohit-Kelkar/SessionManager

Cheers!

--

--