Protecting Sensitive Data Screen in Background in Xamarin Forms

Some Apps like PayPal, WhatsApp, and Banking Apps have a Feature to protect private/sensitive information in the background, so let’s see how we can make something like that in Xamarin Forms.

Let’s Start

let’s start first with iOS, we need to go to the AppDelegate.cs and override OnResignActivation to block the content and OnActivated to unblock the content:

namespace ContentHiderXF.iOS
{
 
    [Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {
        ...
        public override void OnResignActivation(UIApplication application)
        {
            var blurEffect = UIBlurEffect.FromStyle(UIBlurEffectStyle.ExtraDark);
            var blurEffectView = new UIVisualEffectView(blurEffect)
            {
                Frame = application.KeyWindow.Subviews.First().Bounds,
                AutoresizingMask = UIViewAutoresizing.FlexibleDimensions,
                Tag = 12
            };
            application.KeyWindow.Subviews.Last().AddSubview(blurEffectView);
            base.OnResignActivation(application);
        }

        public override void OnActivated(UIApplication uiApplication)
        {
            var sub = uiApplication.KeyWindow?.Subviews.Last();
            if (sub == null)
                return;
            foreach (var vv in sub.Subviews)
            {
                if (vv.Tag == 12)
                    vv.RemoveFromSuperview();
            }
            base.OnActivated(uiApplication);
        }
    }
}

Now for Android we need to go to MainActivity.cs and override OnPause and OnResume:

namespace ContentHiderXF.Droid
{
    [Activity(Label = "ContentHiderXF", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        ...
        protected override void OnResume()
        {
            Window.ClearFlags(WindowManagerFlags.Secure);
            base.OnResume();
        }
        protected override void OnPause()
        {
            Window.SetFlags(WindowManagerFlags.Secure, WindowManagerFlags.Secure);
            base.OnPause();
        }
        ....
    }
}

Result

And that’s all!! You can check the full source code here.

One thought on “Protecting Sensitive Data Screen in Background in Xamarin Forms

Leave a comment