Session Manager

Hello mobile app developers who are here to get some help and reference about how we can manage user sessions inside our MAUI applications.

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).


Create Core Session Manager

At first we need a base class to handle duration, if session has expired, if session is about to end and if is active, so let's create it


The most important part is that you need to declare the class as sealed like this


Then create a singleton to ensure just one instance and make use of that on all life cycle app


After that let's declare some properties to handle methods and initialize those ones.


Almost done, so now we need to create the core handler methods for start, end, extend the session, please add this methods on SessionManager class


That's the difficult part, finally for this handler we need to initialize the Session Duration, and expiration time, so let's do it on the constructor


Alright, that was all for Session Manager, then we have to retrieve those events on our native platforms, let's go first on Android

Android

First let's go to Main Activity file, find OnCreate method and add this code:


Afterwards please add an override for OnUserInteraction, it must be like this:


Finally add those two methods to handle the SessionAlert and SessionExpired events:


Android is ready to test, so we can continue with iOS.


iOS

As we saw on android, let's go to main handler in this case AppDelegate.cs, then we have to modify all of the FinishedLaunching method, it must be like this:


Then we need to handle the SessionAlert and SessionExpired events exactly as android does:



Finally to extend the session on iOS platform we need to add a gesture recognizers on the pages, so for that let's add below AppDelegate a new class called AllGesturesRecognized, I'm gonna leave all the code class here:


Congratulations, now you have an inactivity session handler ready to use depending the bussiness objective, if you enjoyed this article please share it with others !!!!

Share this post