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.

Copy link
Author

Choose a reason for hiding this comment

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

I really have no strong opinion on what naming convention should be done for android-net, but in native Android, it's package.name.ServiceName but it can be addressed relatively in AndroidManifest.xml as .ServiceName. Maybe we should follow that? I think it is still early for this library to think about the naming convention before the inconsistency spreads out even more, but if you think this is the convention we should follow moving forward, I'm happy to revert it.

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

Copy link
Author

Choose a reason for hiding this comment

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

Isn't PascalCasing the standard convention in C# to name consts?

Copy link
Author

Choose a reason for hiding this comment

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

@pictos I've left some comments on some of my code changes.


public const string NotificationChannelId = "Maui.MediaElement";
Copy link
Author

Choose a reason for hiding this comment

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

I have introduced a constant to easily spot the notification ID of this control. I think it's important to keep track of notification ID as we introduce more foreground Android services since the same notification ID could not co-exist in the same Android application. I also think it's important to name them appropriately instead of just "1" as what was previously implemented.

public const string NotificationChannelName = "Transport Controls";
Copy link
Author

Choose a reason for hiding this comment

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

I have also introduced a const for channel name so we can easily track it. This is a user facing text so I think it's better to name it appropriately instead of just "notification". I am not sure about the exact text to put but I think title casing is the norm.


public const int NotificationId = 2024;
Copy link
Author

Choose a reason for hiding this comment

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

2024 I think is unique enough not to clash with other foreground service ID.


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);
Copy link
Author

Choose a reason for hiding this comment

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

I think this operation must be called after setting actions to the notification object, but it's empty at this point and it's the main reason for crash issues reported here. I have also tried including this after the notification action has been set but it just completely hides the buttons in the notification when I tested it so I think it's better to remove this until we have a better reason to keep it and have it implement properly.

}

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();
Copy link
Author

Choose a reason for hiding this comment

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

This is an immutable operation. It basically does nothing so I think it's better to remove it.

}

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