I'm creating MAUI app for Android TV that should work 24/7 without being randomly killed by OS and kinda stuck.
I looked at REQUEST_IGNORE_BATTERY_OPTIMIZATIONS to exclude my app from battery optimization list.
Probably, there's something else I need to do to keep my app alive...
Went thru tens of different manuals, samples and tutorials but none of them worked for me.
I know that REQUEST_IGNORE_BATTERY_OPTIMIZATIONS is not suitable for publishing to Google Play, but I don't need to do that.
I have Android TV API 28 emulator for my development.
my /Platforms/Android/MainApplication.cs looks like this:
[assembly: UsesPermission(Android.Manifest.Permission.RequestIgnoreBatteryOptimizations)]
[Application]
public class MainApplication : MauiApplication { ... }
and /Platforms/Android/MainActivity.cs is:
[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ScreenOrientation = ScreenOrientation.Landscape, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
public class MainActivity : MauiAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
if (OperatingSystem.IsAndroidVersionAtLeast(23) &&
CheckSelfPermission(Android.Manifest.Permission.RequestIgnoreBatteryOptimizations) == Permission.Granted &&
GetSystemService(PowerService) is PowerManager powerManager &&
!powerManager.IsIgnoringBatteryOptimizations(PackageName))
{
var ignoreBatteryOptimizationIntent = new Intent(Settings.ActionRequestIgnoreBatteryOptimizations, Android.Net.Uri.Parse("package:" + PackageName));
StartActivity(ignoreBatteryOptimizationIntent);
}
}
}
But after StartActivity call nothing happens. I expected the OS will ask for whitelist the app.
When I push Android circle button and navigate to Settings/Apps/Special app access/Energy optimization, the switch for my app is still toggled on.
I tried to call StartActivityForResult (with requestCode), and then capturing that result in overridden MainActivity.OnActivityResult by comparing requestCode and surprisingly Result resultCode was Result.Canceled.
I also tried creating NotificationChannel, with PendingIntent that should run and display notification when I do NotificationManagerCompat.From(this).Notify(...) with [assembly: UsesPermission(Android.Manifest.Permission.PostNotifications)] but that code doesn't seem to do anything too - no notification is displayed, no errors, nothing.
My overall goal is to create MAUI Android App that is always running. Maybe, this battery stuff is now what I should be looking for. I use DeviceDisplay.Current.KeepScreenOn = true; and my app is up and running for 10-12 hours with no problem, but then Android decides to kill it. It's not a crash, nor resources over consumption, it's not idle since I have SignalR hub connection alive.