Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix crash when multiple Android Service are active #2418

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,20 @@
namespace CommunityToolkit.Maui.Media.Services;

[SupportedOSPlatform("Android26.0")]
[Service(Exported = false, Enabled = true, Name = "communityToolkit.maui.media.services", ForegroundServiceType = ForegroundService.TypeMediaPlayback)]
[Service(Exported = false, Enabled = true, Name = "CommunityToolkit.Maui.Media.Services", ForegroundServiceType = ForegroundService.TypeMediaPlayback)]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changing the case to uppercase will break older API's compatibility and prevent app from running on Android 23 or below. We only support android 26+ now on media element but I do want to point out this would break some current apps. Also changing this here requires changing the string in the manifest to match which has not been done.

class MediaControlsService : Service
{
public const string ACTION_PLAY = "MediaAction.play";
public const string ACTION_PAUSE = "MediaAction.pause";
public const string ACTION_UPDATE_UI = "CommunityToolkit.Maui.Services.action.UPDATE_UI";
public const string ACTION_UPDATE_PLAYER = "CommunityToolkit.Maui.Services.action.UPDATE_PLAYER";
public const string ACTION_REWIND = "MediaAction.rewind";
public const string ACTION_FASTFORWARD = "MediaAction.fastForward";
public const string ActionPlay = "MediaAction.play";
public const string ActionPause = "MediaAction.pause";
public const string ActionUpdateUI = "CommunityToolkit.Maui.Services.action.UPDATE_UI";
public const string ActionUpdatePlayer = "CommunityToolkit.Maui.Services.action.UPDATE_PLAYER";
public const string ActionRewind = "MediaAction.rewind";
public const string ActionFastForward = "MediaAction.fastForward";
Comment on lines +24 to +29
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why did you change the pattern? Can you revert and follow our pattern


public const string NotificationChannelId = "Maui.MediaElement";
public const string NotificationChannelName = "Transport Controls";

public const int NotificationId = 2024;

bool isDisposed;

Expand All @@ -50,7 +55,7 @@ public override StartCommandResult OnStartCommand([NotNull] Intent? intent, Star

if (!string.IsNullOrEmpty(intent.Action) && receiveUpdates is not null)
{
BroadcastUpdate(ACTION_UPDATE_PLAYER, intent.Action);
BroadcastUpdate(ActionUpdatePlayer, intent.Action);
}

StartForegroundService(intent).AsTask().ContinueWith(t =>
Expand All @@ -69,7 +74,7 @@ public override StartCommandResult OnStartCommand([NotNull] Intent? intent, Star

static void CreateNotificationChannel(NotificationManager notificationMnaManager)
{
var channel = new NotificationChannel("1", "notification", NotificationImportance.Low);
var channel = new NotificationChannel(NotificationChannelId, NotificationChannelName, NotificationImportance.Low);
notificationMnaManager.CreateNotificationChannel(channel);
}

Expand All @@ -91,7 +96,7 @@ ValueTask StartForegroundService(Intent mediaManagerIntent, CancellationToken ca
{
receiveUpdates = new ReceiveUpdates();
receiveUpdates.PropertyChanged += OnReceiveUpdatesPropertyChanged;
LocalBroadcastManager.GetInstance(this).RegisterReceiver(receiveUpdates, new IntentFilter(ACTION_UPDATE_UI));
LocalBroadcastManager.GetInstance(this).RegisterReceiver(receiveUpdates, new IntentFilter(ActionUpdateUI));
}

OnSetupAudioServices();
Expand All @@ -112,20 +117,15 @@ async ValueTask InitializeNotification(MediaSessionCompat mediaSession, Intent m
var style = new AndroidX.Media.App.NotificationCompat.MediaStyle();
style.SetMediaSession(token);

if (Build.VERSION.SdkInt >= BuildVersionCodes.S)
{
style.SetShowActionsInCompactView(0, 1, 2, 3);
}

if (Build.VERSION.SdkInt < BuildVersionCodes.Tiramisu
&& notification is null)
{
notification = new NotificationCompat.Builder(Platform.AppContext, "1");
notification = new NotificationCompat.Builder(Platform.AppContext, NotificationChannelId);
OnSetIntents();
await OnSetContent(mediaManagerIntent, cancellationToken).ConfigureAwait(false);
}

notification ??= new NotificationCompat.Builder(Platform.AppContext, "1");
notification ??= new NotificationCompat.Builder(Platform.AppContext, NotificationChannelId);

notification.SetStyle(style);
notification.SetSmallIcon(_Microsoft.Android.Resource.Designer.Resource.Drawable.exo_styled_controls_audiotrack);
Expand All @@ -142,13 +142,13 @@ async ValueTask InitializeNotification(MediaSessionCompat mediaSession, Intent m

if (OperatingSystem.IsAndroidVersionAtLeast(29))
{
StartForeground(1, notification.Build(), ForegroundService.TypeMediaPlayback);
StartForeground(NotificationId, notification.Build(), ForegroundService.TypeMediaPlayback);
return;
}

if (OperatingSystem.IsAndroidVersionAtLeast(26))
{
StartForeground(1, notification.Build());
StartForeground(NotificationId, notification.Build());
}
}

Expand All @@ -160,16 +160,15 @@ void OnReceiveUpdatesPropertyChanged(object? sender, PropertyChangedEventArgs e)
}
notification.ClearActions();
notification.AddAction(actionPrevious);
if (receiveUpdates.Action is ACTION_PLAY)
if (receiveUpdates.Action is ActionPlay)
{
notification.AddAction(actionPause);
}
if (receiveUpdates.Action is ACTION_PAUSE)
if (receiveUpdates.Action is ActionPause)
{
notification.AddAction(actionPlay);
}
notification.AddAction(actionNext);
notification.Build();
}

void OnSetupAudioServices()
Expand All @@ -195,24 +194,24 @@ async Task OnSetContent(Intent mediaManagerIntent, CancellationToken cancellatio
void OnSetIntents()
{
var pause = new Intent(this, typeof(MediaControlsService));
pause.SetAction("MediaAction.pause");
pause.SetAction(ActionPause);
var pPause = PendingIntent.GetService(this, 1, pause, pendingIntentFlags);
actionPause ??= new NotificationCompat.Action.Builder(Resource.Drawable.exo_controls_pause, ACTION_PAUSE, pPause).Build();
actionPause ??= new NotificationCompat.Action.Builder(Resource.Drawable.exo_controls_pause, ActionPause, pPause).Build();

var play = new Intent(this, typeof(MediaControlsService));
play.SetAction("MediaAction.play");
play.SetAction(ActionPlay);
var pPlay = PendingIntent.GetService(this, 1, play, pendingIntentFlags);
actionPlay ??= new NotificationCompat.Action.Builder(Resource.Drawable.exo_controls_play, ACTION_PLAY, pPlay).Build();
actionPlay ??= new NotificationCompat.Action.Builder(Resource.Drawable.exo_controls_play, ActionPlay, pPlay).Build();

var previous = new Intent(this, typeof(MediaControlsService));
previous.SetAction("MediaAction.rewind");
previous.SetAction(ActionRewind);
var pPrevious = PendingIntent.GetService(this, 1, previous, pendingIntentFlags);
actionPrevious ??= new NotificationCompat.Action.Builder(Resource.Drawable.exo_controls_rewind, ACTION_REWIND, pPrevious).Build();
actionPrevious ??= new NotificationCompat.Action.Builder(Resource.Drawable.exo_controls_rewind, ActionRewind, pPrevious).Build();

var next = new Intent(this, typeof(MediaControlsService));
next.SetAction("MediaAction.fastForward");
next.SetAction(ActionFastForward);
var pNext = PendingIntent.GetService(this, 1, next, pendingIntentFlags);
actionNext ??= new NotificationCompat.Action.Builder(Resource.Drawable.exo_controls_fastforward, ACTION_FASTFORWARD, pNext).Build();
actionNext ??= new NotificationCompat.Action.Builder(Resource.Drawable.exo_controls_fastforward, ActionFastForward, pNext).Build();

notification?.AddAction(actionPrevious);
notification?.AddAction(actionPause);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,8 @@ or PlaybackStateCompat.StateSkippingToQueueItem
currentState = MediaElement.CurrentState;

BroadcastUpdate(newState is MediaElementState.Playing
? MediaControlsService.ACTION_PLAY
: MediaControlsService.ACTION_PAUSE);
? MediaControlsService.ActionPlay
: MediaControlsService.ActionPause);

}

Expand Down Expand Up @@ -333,7 +333,7 @@ protected virtual partial void PlatformPlay()

Player.Prepare();
Player.Play();
BroadcastUpdate(MediaControlsService.ACTION_PLAY);
BroadcastUpdate(MediaControlsService.ActionPlay);
}

protected virtual partial void PlatformPause()
Expand All @@ -344,7 +344,7 @@ protected virtual partial void PlatformPause()
}

Player.Pause();
BroadcastUpdate(MediaControlsService.ACTION_PAUSE);
BroadcastUpdate(MediaControlsService.ActionPause);
}

[Obsolete]
Expand Down Expand Up @@ -651,7 +651,7 @@ void InitializeMediaSession()
mediaSessionConnector.SetPlayer(Player);

uiUpdateReceiver ??= new UIUpdateReceiver(Player);
LocalBroadcastManager.GetInstance(Platform.AppContext).RegisterReceiver(uiUpdateReceiver, new IntentFilter(MediaControlsService.ACTION_UPDATE_PLAYER));
LocalBroadcastManager.GetInstance(Platform.AppContext).RegisterReceiver(uiUpdateReceiver, new IntentFilter(MediaControlsService.ActionUpdatePlayer));

ArgumentNullException.ThrowIfNull(mediaSessionConnector);
ArgumentNullException.ThrowIfNull(Platform.CurrentActivity);
Expand Down Expand Up @@ -721,7 +721,7 @@ void BroadcastUpdate(string action)
{
return;
}
Intent intent = new(MediaControlsService.ACTION_UPDATE_UI);
Intent intent = new(MediaControlsService.ActionUpdateUI);
intent.PutExtra("ACTION", action);
LocalBroadcastManager.GetInstance(Platform.AppContext).SendBroadcast(intent);
}
Expand Down Expand Up @@ -810,22 +810,22 @@ public override void OnReceive(Context? context, Intent? intent)
ArgumentNullException.ThrowIfNull(intent.Action);
ArgumentNullException.ThrowIfNull(player);

if (intent.Action is MediaControlsService.ACTION_UPDATE_PLAYER)
if (intent.Action is MediaControlsService.ActionUpdatePlayer)
{
var action = intent.GetStringExtra("ACTION") ?? string.Empty;
switch (action)
{
case MediaControlsService.ACTION_PLAY:
case MediaControlsService.ActionPlay:
player.Play();
break;
case MediaControlsService.ACTION_PAUSE:
case MediaControlsService.ActionPause:
player.Pause();
break;
case MediaControlsService.ACTION_FASTFORWARD:
case MediaControlsService.ActionFastForward:
player.SeekTo(player.CurrentPosition + 30_000);
player.Play();
break;
case MediaControlsService.ACTION_REWIND:
case MediaControlsService.ActionRewind:
player.SeekTo(player.CurrentPosition - 10_000);
player.Play();
break;
Expand Down
Loading