Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping screen turned on for certain pages

I am using a portable project so do not have direct access to native code.

I have an interface in my project that allows me to access native objects in the Android/iOS projects. We use this primarily for playing audio.

Android, for example, has things like

Window w = new Window();
w.SetFlags(WindowManagerFlags.Fullscreen, WindowManagerFlags.KeepScreenOn);

However the main issue would be accessing a Window object. I could pass a Xamarin.Forms.Page object to the native code, but there would be no way (I don't think) to cast it to a native Android Window object to access the flags.

Is there a way to do this with a portable project?

like image 388
sosil Avatar asked Apr 28 '17 19:04

sosil


2 Answers

You can't do this without platform specific services or renderers. A portable project will have to call platform specific code in order to achieve this.

From that platform specific code, either as a DependencyService or Renderer, you can access the Window object through the Forms.Context. The Forms.Context is your Android Activity, through which you can reach the Window object.

On Android it works like this:

Android.Views.Window window = (Forms.Context as Activity).Window;
window.SetFlags(WindowManagerFlags.KeepScreenOn);

On iOS you can try this (Apple docs):

UIApplication.SharedApplication.IdleTimerDisabled = true;
like image 140
Tim Klingeleers Avatar answered Sep 29 '22 06:09

Tim Klingeleers


Now there is a plugin doing exactly what Tim wrote

https://docs.microsoft.com/en-us/xamarin/essentials/screen-lock

simple source code is here

https://github.com/xamarin/Essentials/blob/main/Samples/Samples/ViewModel/KeepScreenOnViewModel.cs

using System.Windows.Input; using Xamarin.Essentials; using Xamarin.Forms;

namespace Samples.ViewModel
{
    public class KeepScreenOnViewModel : BaseViewModel
    {
        public KeepScreenOnViewModel()
        {
            RequestActiveCommand = new Command(OnRequestActive);
            RequestReleaseCommand = new Command(OnRequestRelease);
        }

        public bool IsActive => DeviceDisplay.KeepScreenOn;

        public ICommand RequestActiveCommand { get; }

        public ICommand RequestReleaseCommand { get; }

        void OnRequestActive()
        {
            DeviceDisplay.KeepScreenOn = true;

            OnPropertyChanged(nameof(IsActive));
        }

        void OnRequestRelease()
        {
            DeviceDisplay.KeepScreenOn = false;

            OnPropertyChanged(nameof(IsActive));
        }
    }
}
like image 30
Emil Avatar answered Sep 29 '22 08:09

Emil