Xamarin Forms - Disable auto-lock when the app is open

后端 未结 5 644
走了就别回头了
走了就别回头了 2020-12-18 17:46

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

5条回答
  •  隐瞒了意图╮
    2020-12-18 18:11

    Xamarin.Forms:

    //show something important, do not sleep
    DependencyService.Get().ExecuteTask("cannotSleep");
    
    //can put in OnDisappearing event
    DependencyService.Get().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;
                }
            }
    }
    

提交回复
热议问题