Skip to content

Android service update#2897

Open
ne0rrmatrix wants to merge 63 commits into
CommunityToolkit:mainfrom
ne0rrmatrix:AndroidServiceUpdate
Open

Android service update#2897
ne0rrmatrix wants to merge 63 commits into
CommunityToolkit:mainfrom
ne0rrmatrix:AndroidServiceUpdate

Conversation

@ne0rrmatrix
Copy link
Copy Markdown
Member

@ne0rrmatrix ne0rrmatrix commented Oct 2, 2025

Description of Change

Switch from using default service implementation to using the recommended by Google. Player and MediaSession in MediaSessionService with MediaController in Activity. The deprecated API's for notifications have been completely removed and are no longer needed.

No change in features with respect to media notifications. The rich media notifications have been significantly overhauled and following best principles. The issue with notification getting stuck and not being removed when leaving page are fixed. When you stop the player the notifications will be removed automatically. If you navigate away from page the notifications will also be removed. It you force close the app by swiping up it will close the notifications and end playback.

The new changes include using a MediaController as an interface to the MediaSessionService which lives in the Activity and fully replaces the player functionality as far as MediaManager is concerned.

Deprecated API's like PlayerNotifications have been removed. The Media Notifications are now handled automatically using MediaSessionService. This has backwards support and is tested from API 26 to 35.

The issue with supporting multiple players has been resolved. I have updated the behaviour to allow for as many mediaElement's as developer wants with support for a service or not.

The current limitations are based entirely on hardware limitation of memory. If you use a CollectionView with 100's or 1000's of mediaElements you will use a ton of memory. The current implementation works fine on a Samsung Tab 8+ but on emulator it crashes for lack of memory and hardware decoders when on the CarouselPage for MediaElement. The crash does not crash the app, just some instances of player where it reaches some arbitrary limit on decoders. This directly impacts playback in emulators and does not appear to be a factor on hardware devices.

  • Fixes #

PR Checklist

  • Has a linked Issue, and the Issue has been approved(bug) or Championed (feature/proposal)
  • Has tests (if omitted, state reason in description)
  • Has samples (if omitted, state reason in description)
  • Rebased on top of main at time of PR
  • Changes adhere to coding standard
  • Documentation created or updated: https://github.com/MicrosoftDocs/CommunityToolkit/pulls

Additional information

Refactored `MediaElement` implementation for Android to replace the bound service (`MediaControlsService`) with `MediaSession` and `MediaController`, simplifying the architecture and aligning with modern Android media playback practices.

- Removed `BoundServiceBinder` and `BoundServiceConnection` classes.
- Updated `MediaControlsService` to use `ExoPlayer` and `MediaSession`.
- Simplified notification management with `NotificationCompat`.
- Refactored `MediaManager` to remove session and bound service logic.
- Added `CreateMediaController` for asynchronous `MediaController` setup.
- Updated `MauiMediaElement` to support `MediaController` integration.
- Removed legacy code, unused imports, and redundant methods.
…gating a second time to same item and now the image does display in notifications. It did not previously. This affects load times. It is now faster.
@ne0rrmatrix ne0rrmatrix added the needs discussion Discuss it on the next Monthly standup label Oct 2, 2025
Comment thread src/CommunityToolkit.Maui.MediaElement/Services/MediaControlsService.android.cs Outdated
- Updated `textureview.xml` to use black backgrounds for better consistency.
- Replaced `RelativeLayout` with `FrameLayout` in `MauiMediaElement.android.cs` for improved layout management.
- Refactored `MediaControlsService.android.cs`:
  - Replaced `static readonly` fields with `const` for immutability.
  - Added audio attributes for better playback handling.
  - Updated track selector to fallback to system language.
  - Added handling for audio interruptions (e.g., unplugging headphones).
- Added `OnTracksChanged` in `MediaManager.android.cs` to manage subtitle button visibility.
- Removed unused imports and redundant constants for cleaner code.
- Improved buffering strategies for smoother playback.
@ne0rrmatrix
Copy link
Copy Markdown
Member Author

The issue with transparent or white background has been fixed! So this is now ready for review :)

@ne0rrmatrix ne0rrmatrix marked this pull request as ready for review October 2, 2025 21:41
Copilot AI review requested due to automatic review settings October 2, 2025 21:41
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR modernizes the Android MediaElement implementation by replacing the deprecated service architecture with Google's recommended MediaSessionService approach. The changes migrate from using ExoPlayer directly to using MediaController with MediaSessionService, implementing proper lifecycle management and unified media notifications.

Key changes include:

  • Replaced ExoPlayer with MediaController as the platform media element
  • Implemented MediaSessionService pattern for background media playback
  • Unified media notifications using native Android methods instead of custom implementations

Reviewed Changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
MediaManager.shared.cs Updated global using alias from IExoPlayer to MediaController
MediaManager.android.cs Complete overhaul replacing ExoPlayer with MediaController, removed service binding logic
MauiMediaElement.android.cs Refactored layout from RelativeLayout to FrameLayout, added MediaController integration
MediaControlsService.android.cs Converted from Service to MediaSessionService with proper notification handling
BoundServiceConnection.android.cs File deleted - service binding no longer needed
BoundServiceBinder.android.cs File deleted - service binding no longer needed
textureview.xml Changed background colors from white/transparent to black
MediaElementHandler.android.cs Added async MediaController creation and connection logic
AppBuilderExtensions.shared.cs Removed MediaControlsService dependency injection

Comment thread src/CommunityToolkit.Maui.MediaElement/Views/MediaManager.android.cs Outdated
Comment thread src/CommunityToolkit.Maui.MediaElement/Views/MediaManager.android.cs Outdated
Comment thread src/CommunityToolkit.Maui.MediaElement/Views/MediaManager.android.cs Outdated
Comment thread src/CommunityToolkit.Maui.MediaElement/Views/MediaManager.android.cs Outdated
ne0rrmatrix and others added 7 commits October 2, 2025 14:43
…oid.cs


Good catch

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
…oid.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Updated the CreateMediaController method to include an optional
CancellationToken parameter, allowing the operation to be canceled
if needed. Modified the WaitAsync call to respect the provided
cancellation token, improving the method's flexibility and
robustness.
@ne0rrmatrix ne0rrmatrix removed the needs discussion Discuss it on the next Monthly standup label Oct 30, 2025
Copilot AI review requested due to automatic review settings November 20, 2025 11:22
@ne0rrmatrix
Copy link
Copy Markdown
Member Author

If we choose to continue supporting many video's being able to play simultaneously this PR will be closed as incompatible. I do not see any way to implement that. It is neither intended or recommended that anyone ever have more than one player.

@KeithBoynton
Copy link
Copy Markdown

What is the state of play with this guys? Parts of this PR fixes an issue I have with the Android implemention of my app. Right now I'm having to build from the PR when releasing the Android verison of my app and the Nuget version for all other platforms.

What is the hold up to getting this merged in and released?

Copilot AI review requested due to automatic review settings January 8, 2026 20:02
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 10 out of 10 changed files in this pull request and generated 4 comments.

Comment thread src/CommunityToolkit.Maui.MediaElement/Services/MediaControlsService.android.cs Outdated
@TheCodeTraveler TheCodeTraveler added breaking change This label is used for PRs that include a breaking change and removed needs discussion Discuss it on the next Monthly standup labels Jan 8, 2026
@dotnet-policy-service dotnet-policy-service Bot added stale The author has not responded in over 30 days help wanted This proposal has been approved and is ready to be implemented labels Feb 13, 2026
ne0rrmatrix added 12 commits May 1, 2026 00:57
Refactor Android media playback to give each MediaElement its own ExoPlayer/MediaSession, identified by a unique AndroidPlayerId. MediaControlsService now manages multiple player registrations, allowing independent creation, release, and disposal of players. Add MediaSessionCallback and TaskListenableFuture to support custom commands and async interop. Update MediaManager, MediaElement, and handlers for this model, including improved resource cleanup and error handling. Update csproj for required Android resources. Includes minor refactoring for reliability.
Updated Xamarin.AndroidX.Media3.* NuGet packages from 1.8.0 to 1.10.0. Refactored CreatePlatformPlayer to use async/await for improved readability. Made minor formatting adjustments for consistency. No functional changes outside of version bump and async refactor.
Replaced custom TaskListenableFuture with AndroidX's ResolvableFuture in MediaSessionCallback for handling custom commands. Removed TaskListenableFuture class and updated OnCustomCommand to use the new future implementation, simplifying async result handling and reducing custom code.
Aligned the indentation of future.Set(new SessionResult(SessionResult.ResultSuccess)); to match the surrounding code block for improved readability. No functional changes were made.
Refactor code formatting and indentation for readability and consistency. Reformat exception handling and method signatures to follow C# conventions.

Refactor Android media player for async and artwork support

Refactored media player methods to use async/await for better responsiveness and resource management. Artwork is now fetched asynchronously from URLs or files and embedded in media metadata. Added helper for artwork retrieval, improved exception handling, and ensured player cleanup in OnDestroy. Minor code style improvements included.
Replaced ResolvableFuture with CallbackToFutureAdapter and introduced a sealed FutureResolver class to handle custom commands asynchronously. Moved ReleasePlayer logic and exception handling into FutureResolver.AttachCompleter for improved clarity and error management. The method now returns the custom command's action string as a tag.
Explicitly check for null result from SendCustomCommand.Get() and throw a descriptive exception. This enhances error clarity and robustness in player release logic.
Refactored Android media playback to align with Media3 event model. Deprecated OnPlayerStateChanged in favor of OnPlaybackStateChanged and OnIsPlayingChanged. Centralized player pausing logic and improved state transitions. Updated PlatformPlay and PlatformStop to follow Media3 contracts. Ensured proper listener detachment and resource cleanup in Dispose.
@ne0rrmatrix ne0rrmatrix marked this pull request as ready for review May 10, 2026 13:56
@ne0rrmatrix
Copy link
Copy Markdown
Member Author

This PR is finally ready for review and all the issues that I have found with it are now fixed! The issue with playback in a CollectionView or a CarouselView are fixed. The only existing issues are related to emulator limitations. Please test with a real device when testing CarouselView as it will have issues in emulator with so many players. I will note the current behavior with Carousels are also present in main. So testing on hardware device will mitigate those issues.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 15 out of 15 changed files in this pull request and generated 2 comments.

Comment thread src/CommunityToolkit.Maui.MediaElement/Views/MauiMediaElement.android.cs Outdated
Enhance resource management by properly disposing views and unsubscribing events in MediaElementHandler and MauiMediaElement. Add CancellationTokenSource to MediaManager to handle concurrent source updates and prevent race conditions. Update SetPlayerData and CreateMediaItem to support cancellation. Improve cleanup logic to avoid memory leaks and maintain correct view hierarchy.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

breaking change This label is used for PRs that include a breaking change help wanted This proposal has been approved and is ready to be implemented stale The author has not responded in over 30 days

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants