4

I want to disable auto-lock when my app is open. How can I do that?

  • this will be platform specific: https://stackoverflow.com/questions/12661004/how-to-disable-enable-the-sleep-mode-programmatically-in-ios – Jason Nov 29 '18 at 06:22
  • https://developer.android.com/training/scheduling/wakelock – Jason Nov 29 '18 at 06:23

6 Answers6

12

https://learn.microsoft.com/en-my/xamarin/essentials/device-display?tabs=android

Just need to set DeviceDisplay.KeepScreenOn to true/false in any page and it will work. There is no need to go into individual platform.

You'll have to set permission WAKE_LOCK in Android though.

*Moderator, I have deleted my answer on another post. This is a more relevant post for answer.

TPG
  • 2,811
  • 1
  • 31
  • 52
4

UPDATE

The answer below was a little old the better and easy way to do it now is using essentials and setting the following property:

DeviceDisplay.KeepScreenOn= true; 

OG ANSWER

For iOS, you need to override the DidFinishLaunchingWithOptions method in your Appdelegate class:

 public override bool FinishedLaunching(UIApplication uiApplication, NSDictionary launchOptions)
    {
       UIApplication.SharedApplication.IdleTimerDisabled = true;
       ....
    } 

For Android, you need to do the following things in your MainActivity for it:

you have to declare this uses-permission on AndroidManifest:

<uses-permission android:name="android.permission.WAKE_LOCK" />

Create a global field for WakeLock using static Android.OS.PowerManager;;

private WakeLock wakeLock;

And in your OnResume:

PowerManager powerManager = (PowerManager)this.GetSystemService(Context.PowerService);
WakeLock wakeLock = powerManager.NewWakeLock(WakeLockFlags.Full, "My Lock");
wakeLock.Acquire();

Just remember to release this lock when your application is paused or destroyed by doing this:

wakeLock.Release();

Usually, it's suggested to call the acquire method inside the onResume() of your activity and the release method in onPause(). This way we guarantee that our application still performs well in the case of being paused or resumed.

Goodluck revert in case of queries

FreakyAli
  • 13,349
  • 3
  • 23
  • 63
  • I saw an article about using xamarin essentials i dont know if that solution is implemented in all my views or do I have to implement it one by one –  Nov 29 '18 at 06:37
  • the article is here : https://learn.microsoft.com/en-us/xamarin/essentials/screen-lock?context=xamarin/xamarin-forms –  Nov 29 '18 at 06:38
  • You have to implement it in just one, MainActivity for Android and Appdelegate for iOS!! Are you sure you read the answer? – FreakyAli Nov 29 '18 at 06:44
  • I mean the code in the article do I have to implement it once or one by one? –  Nov 29 '18 at 06:47
  • I am not sure i have not used this API of Xamarin Essentials but i have posted the answer of what i have used and what works well for me – FreakyAli Nov 29 '18 at 06:48
  • For iOS can't you just set true/false UIApplication.SharedApplication.IdleTimerDisabled at runtime?.. – Nick Kovalsky Nov 29 '18 at 07:58
  • @NickKovalsky You can in native iOS but not when you are in your Xamarin forms code now can you? – FreakyAli Nov 29 '18 at 08:02
  • Yeah that's what i do in xamarin, ill post an answer for this – Nick Kovalsky Nov 29 '18 at 08:05
  • Added an answer with the solution im actually using – Nick Kovalsky Nov 29 '18 at 08:22
  • @G.hakim Thank you for your answer this one works. Can you help me with the logic of my synchronization? the link is: https://stackoverflow.com/questions/53581483/how-to-fix-bi-directional-synchronization –  Dec 02 '18 at 15:22
  • @LawrenceAgulto sure give me a min to have a look – FreakyAli Dec 03 '18 at 05:51
4

Xamarin.Forms:

//show something important, do not sleep
DependencyService.Get<INativeTasks>().ExecuteTask("cannotSleep");

//can put in OnDisappearing event
DependencyService.Get<INativeTasks>().ExecuteTask("canSleep");

Native tasks helper:

 public interface INativeTasks
    {
        ...
        void ExecuteTask(string task, object param=null);
        ...
    }

Android:

Global variables and other..

public class DroidCore
{
    private static DroidCore instance;
    public static DroidCore Current
    {
        get { return instance ?? (instance = new DroidCore()); }
    }

    public static Window MainWindow { get; set; }
    ...
}

MainActivity.cs

protected override void OnCreate(Bundle bundle)
{
...        
DroidCore.Current.MainView = this.Window.DecorView;
...
}

Native helpers:

public class NativeTasks : INativeTasks
    {
    public void ExecuteTask(string task, object param = null)
    {
            switch (task)
            {

                ... //any native stuff you can imagine

            case "cannotSleep":
                DroidCore.MainWindow.AddFlags(WindowManagerFlags.KeepScreenOn);
                break;

            case "canSleep":
                DroidCore.MainWindow.ClearFlags(WindowManagerFlags.KeepScreenOn);
                break;
            }
        }
}

iOS:

Native helpers:

public class NativeTasks : INativeTasks
    {
    public void ExecuteTask(string task, object param = null)
    {
            switch (task)
            {

                ... //any native stuff you can imagine

            case "cannotSleep":
                UIApplication.SharedApplication.IdleTimerDisabled = true;
                break;

            case "canSleep":
                UIApplication.SharedApplication.IdleTimerDisabled = false;
                break;
            }
        }
}
Nick Kovalsky
  • 5,378
  • 2
  • 23
  • 50
  • I am curious about something here! Why write a renderer for something like this? if you want an application wide disabled auto-lock like the questioner has asked for just curious! – FreakyAli Nov 29 '18 at 08:27
  • Native tasks are just for everything you can't do in forms. Have many other tasks implemented, posted the part you were asking for. Now when you hit the Forms wall with any native problem just put your native code inside INativeTasks and fly. :) – Nick Kovalsky Nov 29 '18 at 08:39
2

We can achieve it by using Xamarin.Essentials plugin. Install it on solution level(While installing select include prerelease checkbox).

In your MainPage write this code

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
        ToggleScreenLock();
    }
    public void ToggleScreenLock()
    {
        if (!ScreenLock.IsActive)
            ScreenLock.RequestActive();
        else
            ScreenLock.RequestRelease();
    }
}

In Android project MainActivity add this line

Xamarin.Essentials.Platform.Init(this, savedInstanceState);

before calling LoadApplication(new App());. For more information visit Microsoft docs.

This is working throughout the app. To install plugin refer below screenshot -

enter image description here

R15
  • 13,982
  • 14
  • 97
  • 173
1

Since the accepted answer is deprecated in android

Below code works for me in Xamarin.Android

Window window = ((MainActivity)Forms.Context).Window;
window.AddFlags(WindowManagerFlags.KeepScreenOn);
Nihas Nizar
  • 619
  • 8
  • 15
0

For newer android versions, you may use this:

Window.AddFlags(WindowManagerFlags.KeepScreenOn);
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 10 '22 at 10:55