From 440e4e28cfa6445f27308dc192ce495a5a0e0b78 Mon Sep 17 00:00:00 2001 From: James Crutchley Date: Fri, 16 Aug 2024 05:01:00 -0700 Subject: [PATCH] Enhance service lifecycle and exit strategy (#2039) * Enhance service lifecycle and exit strategy - Updated `AndroidManifest.xml` to improve `CommunityToolkit.Maui.Media.Services` behavior. Added `android:stopWithTask=true` and `android:foregroundServiceType=mediaPlayback` attributes to ensure the service stops with the task and properly manages media playback in the foreground. - Added `OnDestroy()` method in `MediaControlsService.android.cs` for a more aggressive shutdown approach. This includes logging service destruction, stopping and removing the service from the foreground, finishing and removing the task, exiting the application, and ensuring base class cleanup with `base.OnDestroy()`. This aims at a cleaner exit and resource management when the service is destroyed. * Fix Merge error --------- Co-authored-by: Brandon Minnick <13558917+brminnick@users.noreply.github.com> Co-authored-by: Gerald Versluis --- .../Platforms/Android/AndroidManifest.xml | 2 +- .../Services/MediaControlsService.android.cs | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/samples/CommunityToolkit.Maui.Sample/Platforms/Android/AndroidManifest.xml b/samples/CommunityToolkit.Maui.Sample/Platforms/Android/AndroidManifest.xml index e4c429ce33..f592b7edac 100644 --- a/samples/CommunityToolkit.Maui.Sample/Platforms/Android/AndroidManifest.xml +++ b/samples/CommunityToolkit.Maui.Sample/Platforms/Android/AndroidManifest.xml @@ -2,7 +2,7 @@ - diff --git a/src/CommunityToolkit.Maui.MediaElement/Services/MediaControlsService.android.cs b/src/CommunityToolkit.Maui.MediaElement/Services/MediaControlsService.android.cs index 629c8bfa72..810c793e2e 100644 --- a/src/CommunityToolkit.Maui.MediaElement/Services/MediaControlsService.android.cs +++ b/src/CommunityToolkit.Maui.MediaElement/Services/MediaControlsService.android.cs @@ -217,6 +217,15 @@ void OnSetIntents() notification?.AddAction(actionNext); } + public override void OnDestroy() + { + Platform.CurrentActivity?.StopService(new Intent(Platform.AppContext, typeof(MediaControlsService))); + System.Diagnostics.Trace.TraceInformation("MediaControlsService destroyed."); + Platform.CurrentActivity?.FinishAndRemoveTask(); + System.Environment.Exit(0); + System.Diagnostics.Trace.TraceInformation("Application exiting."); + base.OnDestroy(); + } static void BroadcastUpdate(string receiver, string action) { if (Build.VERSION.SdkInt >= BuildVersionCodes.Tiramisu)