Xamarin.Forms: How to prevent Android from auto-locking

Updated on 31st May 2020

Sometimes we want our applications to stay focused on screen and prevent the screen from locking & sleeping, especially on unattended applications.

You can usually configure a lock & sleep timer from within the Android Settings menu however we don't always have the ability to change settings before our app is used by the user. Therefore we need a way to configure our app to force Android to stay awake.

This is very simple in Xamarin.Forms when using Xamarin.Essentials.

Install Nuget Package

If you don't already have it installed, start by installing the Xamarin.Essentials Nuget package in the Android project. If you are using Visual Studio then you may search for the package using the Nuget package manager, or alternatively via the command line by typing:

Install-Package Xamarin.Essentials

And then reference it from the top of your MainActivity.cs file within the Android project.

using Xamarin.Essentials;

Setting the Permissions

The WAKE_LOCK permission needs to be enabled inside the manifest file. If you're using Visual Studio then right click on the Android project and choose the "properties" option.

Now in the Android Manifest tab, look for the "Required Permissions" area where you will search for WAKE_LOCK and enable it. Then save the file.

Xamarin android wake lock

Write the Code

Create a method called ToggleScreenLock which will keep the screen awake.

        public void ToggleScreenLock()
        {
            DeviceDisplay.KeepScreenOn = true;
        }

Now reference the newly created method from within the OnCreate method.

        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;
            this.Window.AddFlags(WindowManagerFlags.Fullscreen);
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

            ToggleScreenLock();

            LoadApplication(new App());
        }

Your application should now stay awake and prevent the screen from locking when there hasn't been any activity from the user.


Article Categories: # xamarin # xamarin.forms # .net

About

A tech blog by Andy P. I talk about coding, enterprise software development, tech, games design & other things that interest me.

Signup To The Newsletter

I try to post a new interesting article every saturday.