KeepScreenOn throws error on Android

Jassim Al Rahma 1,521 Reputation points
2023-03-15T19:56:19+00:00

Hi,

I am trying the following:

DeviceDisplay.KeepScreenOn = true;

inside the App,xaml.cs and it's working fine on iOS but when I run it on Android I get below error:

System.NullReferenceException: The current Activity can not be detected. Ensure that you have called Init in your Activity or Application class.
  at Microsoft.Maui.ApplicationModel.ActivityStateManagerExtensions.GetCurrentActivity(IActivityStateManager manager, Boolean throwOnNull) in D:\a\_work\1\s\src\Essentials\src\Platform\ActivityStateManager.android.cs:95
  at Microsoft.Maui.Devices.DeviceDisplayImplementation.SetKeepScreenOn(Boolean keepScreenOn) in D:\a\_work\1\s\src\Essentials\src\DeviceDisplay\DeviceDisplay.android.cs:28
  at Microsoft.Maui.Devices.DeviceDisplayImplementationBase.set_KeepScreenOn(Boolean value) in D:\a\_work\1\s\src\Essentials\src\DeviceDisplay\DeviceDisplay.shared.cs:106
  at Microsoft.Maui.Devices.DeviceDisplay.set_KeepScreenOn(Boolean value) in D:\a\_work\1\s\src\Essentials\src\DeviceDisplay\DeviceDisplay.shared.cs:56
  at DataEye.App..ctor() in /Users/jassim/Projects/DataEye/DataEye/App.xaml.cs:17
  at at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
  at at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
  at at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2[[Microsoft.Extensions.DependencyInjection.ServiceLookup.RuntimeResolverContext, Microsoft.Extensions.DependencyInjection, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60],[System.Object, System.Private.CoreLib, Version=7.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].VisitCallSiteMain(ServiceCallSite callSite, RuntimeResolverContext argument)
  at at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite callSite, RuntimeResolverContext context)
  at at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2[[Microsoft.Extensions.DependencyInjection.ServiceLookup.RuntimeResolverContext, Microsoft.Extensions.DependencyInjection, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60],[System.Object, System.Private.CoreLib, Version=7.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].VisitCallSite(ServiceCallSite callSite, RuntimeResolverContext argument)
  at at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
  at at Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(Type serviceType)
  at at System.Collections.Concurrent.ConcurrentDictionary`2[[System.Type, System.Private.CoreLib, Version=7.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Func`2[[Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope, Microsoft.Extensions.DependencyInjection, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60],[System.Object, System.Private.CoreLib, Version=7.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=7.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].GetOrAdd(Type key, Func`2 valueFactory)
  at at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
  at at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
  at Microsoft.Maui.MauiContext.WrappedServiceProvider.GetService(Type serviceType) in D:\a\_work\1\s\src\Core\src\MauiContext.cs:68
  at Microsoft.Maui.MauiContext.WrappedServiceProvider.GetService(Type serviceType) in D:\a\_work\1\s\src\Core\src\MauiContext.cs:68
  at at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[IApplication](IServiceProvider provider)
  at at Microsoft.Maui.Hosting.SentryMauiAppBuilderExtensions.BindMauiEvents(IPlatformApplication platformApplication)
  at at Microsoft.Maui.Hosting.SentryMauiAppBuilderExtensions.<>c.<RegisterMauiEventsBinder>b__3_2(Application application)
  at Microsoft.Maui.MauiApplication.<OnCreate>b__2_0(OnApplicationCreating del) in D:\a\_work\1\s\src\Core\src\Platform\Android\MauiApplication.cs:35
  at Microsoft.Maui.LifecycleEvents.LifecycleEventServiceExtensions.InvokeLifecycleEvents[OnApplicationCreating](IServiceProvider services, Action`1 action) in D:\a\_work\1\s\src\Core\src\LifecycleEvents\LifecycleEventServiceExtensions.cs:31
  at Microsoft.Maui.MauiApplication.OnCreate() in D:\a\_work\1\s\src\Core\src\Platform\Android\MauiApplication.cs:35
  at Android.App.Application.n_OnCreate(IntPtr jnienv, IntPtr native__this) in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/obj/Release/net7.0/android-33/mcw/Android.App.Application.cs:1072
  at Android.Runtime.JNINativeWrapper.Wrap_JniMarshal_PP_V(_JniMarshal_PP_V callback, IntPtr jnienv, IntPtr klazz) in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Android.Runtime/JNINativeWrapper.g.cs:22

KIndly help..

Thanks,

Jassim

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,857 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 68,261 Reputation points Microsoft Vendor
    2023-03-23T09:38:14.2966667+00:00

    Hello,

    From MAUI github issue:DeviceDisplay.Current.KeepScreenOn = true isn't working

    It is a timing issue. The actual implementation of KeepScreenOn in Android depends on setting WindowManagerFlags on the current Activity's Window; if KeepScreenOn = true is called in the cross-platform application before the Window is actually available, then it won't do anything.

    Here is a solution, you can put this code to the windows create method like following code.

    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();       
            MainPage = new AppShell();
        }
       protected override Window CreateWindow(IActivationState activationState)
        {
            Window window = base.CreateWindow(activationState);
    
           window.Created += (s, e) =>
            {
                DeviceDisplay.KeepScreenOn = true;
            };
    
           return window;
        }
    
    }
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. Auto 46 Reputation points
    2024-04-17T14:36:53.6866667+00:00

    I used to call (DeviceDisplay.KeepScreenOn = true) in the constructor of the page and now - on Android with .NET MAUI - I get the same error:

    "The current Activity can not be detected. Ensure that you have called Init in your Activity or Application class."

    To solve the problem I did in this way at the end of the constuctor of the page:

    MainThread.BeginInvokeOnMainThread(async () =>
    {
        await Task.Delay(1500);  
        DeviceDisplay.KeepScreenOn = true;
    });
    
    0 comments No comments