Maui icon indicating copy to clipboard operation
Maui copied to clipboard

[BUG] - MediaElement DisconnectHandler Crash Android App

Open jhovelnu opened this issue 1 year ago • 16 comments

Is there an existing issue for this?

  • [X] I have searched the existing issues

Did you read the "Reporting a bug" section on Contributing file?

  • [X] I have read the "Reporting a bug" section on Contributing file: https://github.com/CommunityToolkit/Maui/blob/main/CONTRIBUTING.md#reporting-a-bug

Current Behavior

Calling the DisconnectHandler of the mediaElement:

protected override async void OnDisappearing() { base.OnDisappearing();

// Stop and cleanup MediaElement when we navigate away
if (uxMediaElement.IsVisible)
{
    await Task.Delay(500); //This is to avoid crash Disposed object 
    uxMediaElement.Handler?.DisconnectHandler();
}

}

With the Version 4.0.1 this code was working well, i had to add the Delay because the app crashes.

But with the last version 4.1.0 my app always crashing when i call the DisconnectHandler method, i have tried to remove the Delay and use the Unloaded event of the Content Page but the error still ocurrs.

Expected Behavior

The DisconnectHandler working well without app crash

Steps To Reproduce

1 - Add the Toolkit:MediaElement to a Page 2 - Configure any video file to reproduce 3 - Navigate to other page 4 - Call the DisconnectHandler in the page (Step 2) 5 - Then the app crash

Link to public reproduction project repository

https://github.com/jhovelnu/MauiApp1/tree/MediaElement_Test

Environment

- .NET MAUI CommunityToolkit:4.1.0
- OS: Android
- .NET MAUI: 8.0.82

Anything else?

No response

jhovelnu avatar Sep 10 '24 15:09 jhovelnu

Hi this is the repo to test.

https://github.com/jhovelnu/MauiApp1/tree/MediaElement_Test

However i couldnt reproduce this error in the test project.

But i found something.

In the Test project when i play the video:

image

But when i play a video in my real project i see this:

image

Could this be the cause of the error?

This is the stack trace in app center:

System.ObjectDisposedException System.ObjectDisposedException: Cannot access a disposed object. Object name: 'CommunityToolkit.Maui.Core.Views.MauiMediaElement'.

Java.Interop.JniPeerMembers.AssertSelf(IJavaPeerable self) Java.Interop.JniPeerMembers.JniInstanceMethods.InvokeVirtualVoidMethod(String encodedMember, IJavaPeerable self, JniArgumentValue* parameters) Android.Views.ViewGroup.RemoveView(View view) Microsoft.Maui.WindowOverlay.DeinitializePlatformDependencies() Microsoft.Maui.WindowOverlay.Deinitialize() Microsoft.Maui.VisualDiagnosticsOverlay.Deinitialize() Microsoft.Maui.Handlers.WindowHandler.OnRootViewChanged(Object sender, EventArgs e) Microsoft.Maui.Platform.NavigationRootManager.OnWindowContentPlatformViewCreated() Microsoft.Maui.Platform.NavigationRootManager.ElementBasedFragment.OnViewCreated(View view, Bundle savedInstanceState) AndroidX.Fragment.App.Fragment.n_OnViewCreated_Landroid_view_View_Landroid_os_Bundle_(IntPtr jnienv, IntPtr native__this, IntPtr native_view, IntPtr native_savedInstanceState) Android.Runtime.JNINativeWrapper.Wrap_JniMarshal_PPLL_V(_JniMarshal_PPLL_V callback, IntPtr jnienv, IntPtr klazz, IntPtr p0, IntPtr p1)

jhovelnu avatar Sep 18 '24 16:09 jhovelnu

That repository does not exist

ne0rrmatrix avatar Sep 18 '24 20:09 ne0rrmatrix

Sorry @ne0rrmatrix the repository was private, i have changed it to public already

jhovelnu avatar Sep 18 '24 21:09 jhovelnu

Your android manifest is missing some requirements. Can you look at this page: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/views/mediaelement?tabs=android and update the manifest with missing data. Please update the https://github.com/jhovelnu/MauiApp1/blob/MediaElement_Test/Platforms/Android/MainActivity.cs with ResizeableActivity = true,.

ne0rrmatrix avatar Sep 18 '24 21:09 ne0rrmatrix

@ne0rrmatrix

Hi, it's true that some things are missing in the MainActivity and the Manifest compared to the documentation. However, in the test project I shared, I haven't been able to replicate the error that does occur in my production application, and it happens when a new MainPage is set.

In the test project, I tried to recreate the processes I perform in my production application, but the error does not replicate. Therefore, it is challenging to provide an explanation of what might be happening.

Additionally, in my production project, I already tested adding the missing information to the Manifest and MainActivity, but the error persists.

I will continue testing and investigating what might be causing the error, and if I find the cause, I will share it in this same thread.

jhovelnu avatar Sep 19 '24 00:09 jhovelnu

I dont know if this is relevant, but after updating 4.1.1 im starting to get this crash in production: image

image

And we dont care about the foreground service at all, we just show some introduction videos.

** Update, it just happend on version 4.0.1 aswell.

br.

Pmr-precure avatar Sep 19 '24 12:09 Pmr-precure

@ne0rrmatrix

Hi, it's true that some things are missing in the MainActivity and the Manifest compared to the documentation. However, in the test project I shared, I haven't been able to replicate the error that does occur in my production application, and it happens when a new MainPage is set.

In the test project, I tried to recreate the processes I perform in my production application, but the error does not replicate. Therefore, it is challenging to provide an explanation of what might be happening.

Additionally, in my production project, I already tested adding the missing information to the Manifest and MainActivity, but the error persists.

I will continue testing and investigating what might be causing the error, and if I find the cause, I will share it in this same thread.

https://github.com/Pmr-precure/MediaElementDispose.git Can you try clone this and test? Just press the button a couple of time and see it crashes.

BR.

Pmr-precure avatar Sep 20 '24 07:09 Pmr-precure

Sorry for spamming your thread, but ive done some testing, and this is what i got: https://github.com/Pmr-precure/MediaElementDispose.git This will crash when changing mainpage. Adding a delay before disposing seems to fix this?

But then adding ForegroundService + delay seems to cause: image Try this sample: https://github.com/Pmr-precure/MediaElementDispose/tree/withForegroundAndDelay

In our app we use a foreground service to monitor some BLE devices. And videos are just tutorials.

Pmr-precure avatar Sep 20 '24 07:09 Pmr-precure

Sorry for spamming your thread, but ive done some testing, and this is what i got: https://github.com/Pmr-precure/MediaElementDispose.git This will crash when changing mainpage. Adding a delay before disposing seems to fix this?

But then adding ForegroundService + delay seems to cause: image Try this sample: https://github.com/Pmr-precure/MediaElementDispose/tree/withForegroundAndDelay

In our app we use a foreground service to monitor some BLE devices. And videos are just tutorials.

I looked at your sample. It is missing the required permissions and service in the android manifest. Please look at the instructions here: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/views/mediaelement?tabs=android

ne0rrmatrix avatar Sep 20 '24 08:09 ne0rrmatrix

Sorry for spamming your thread, but ive done some testing, and this is what i got: https://github.com/Pmr-precure/MediaElementDispose.git This will crash when changing mainpage. Adding a delay before disposing seems to fix this? But then adding ForegroundService + delay seems to cause: image Try this sample: https://github.com/Pmr-precure/MediaElementDispose/tree/withForegroundAndDelay In our app we use a foreground service to monitor some BLE devices. And videos are just tutorials.

I looked at your sample. It is missing the required permissions and service in the android manifest. Please look at the instructions here: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/views/mediaelement?tabs=android

I updated the samples and added the permissions + service. But its still the same.

Pmr-precure avatar Sep 20 '24 10:09 Pmr-precure

The dispose "bug" only seems happen when using App.Current.Mainpage = new page, going from 1 page with a MediaElement to a new page.

Probably an issue in the MAUI core when setting the MainPage it will try to access the old one again? dunno. But setting the delay seems to do the job.

Pmr-precure avatar Sep 23 '24 10:09 Pmr-precure

@ne0rrmatrix I did some more digging, and the error happens in the RemoveView method in Microsoft.Maui core. image

image

The "bug" would be fixed if there was a try catch like ive done. But no idea if that would be fine. So it seems like its trying to remove the already disposed MediaElement.

Pmr-precure avatar Sep 24 '24 09:09 Pmr-precure

I'm currently migrating media element to media 3 library. If you can test against this PR: https://github.com/CommunityToolkit/Maui/pull/2076 it would be appreciated. Any fix applied and merged to main would unlikely ever make it to a Nuget for current media 2 version. Any feedback on PR would be appreciated. Oh and if u remove the permissions for notifications it should just not start the service now. So if you want to disable notifications it will just disable service.

ne0rrmatrix avatar Sep 24 '24 09:09 ne0rrmatrix

I'm currently migrating media element to media 3 library. If you can test against this PR: #2076 it would be appreciated. Any fix applied and merged to main would unlikely ever make it to a Nuget for current media 2 version. Any feedback on PR would be appreciated. Oh and if u remove the permissions for notifications it should just not start the service now. So if you want to disable notifications it will just disable service.

Great! Ill test right away.

"Oh and if u remove the permissions for notifications it should just not start the service now. So if you want to disable notifications it will just disable service" - But in our case, we already have a foreground permission since we use it for some BLE stuff, so we have no way of disabling this right? (Probably not a big deal anyways but.)

Pmr-precure avatar Sep 24 '24 09:09 Pmr-precure

@ne0rrmatrix Your PR did the trick with the ForegroundDidNotStartInTime exception! yay.

It didnt fix the "Cannot access disposed object", but putting a delay before the disconnecthandler fixes that. Since then it wont be disposed before the removeView gets called.

Thanks for your great work.

Pmr-precure avatar Sep 24 '24 10:09 Pmr-precure

I'm currently migrating media element to media 3 library. If you can test against this PR: #2076 it would be appreciated. Any fix applied and merged to main would unlikely ever make it to a Nuget for current media 2 version. Any feedback on PR would be appreciated. Oh and if u remove the permissions for notifications it should just not start the service now. So if you want to disable notifications it will just disable service.

Great! Ill test right away.

"Oh and if u remove the permissions for notifications it should just not start the service now. So if you want to disable notifications it will just disable service" - But in our case, we already have a foreground permission since we use it for some BLE stuff, so we have no way of disabling this right? (Probably not a big deal anyways but.)

If you create a discussion with a feature request to add the ability to disable notifications I will look at it. It is a feature I think would be a good idea. If you can get 10 up-votes in the next day or two I will start getting it ready and try and talk to the team about adding it. Up-voting features lets me push things through easier.

ne0rrmatrix avatar Sep 24 '24 10:09 ne0rrmatrix

@Pmr-precure @ne0rrmatrix

Hello, hasn't this issue been resolved yet? In my case, even though a 'Delay' is configured, in some scenarios it doesn't work and the application closes.

In my production application, there are more than 2000 user errors where the application crashes due to this issue.

Is there any workaround other than using Delay?

Image

Image

jhovelnu avatar Oct 24 '24 15:10 jhovelnu

Can you check and see if this PR fixes your issue? https://github.com/CommunityToolkit/Maui/pull/2076 If it does not can you get back to me.

ne0rrmatrix avatar Oct 24 '24 15:10 ne0rrmatrix

Hi,

I’m experiencing crashes related to MauiMediaElement in the following setup:

Environment:

  • Package: <PackageReference Include="CommunityToolkit.Maui.MediaElement" Version="4.1.2" />
  • Android Version: Android 12 (SDK 31)
  • Device: OPPO OP4C41L1 (X2 Lite)

Usage Details:

  • I’m using MauiMediaElement in two pages (LoneWorkingPage and PreferencesPage) to play local MP3 files embedded in the app. The MediaElement is not visible as it’s solely used to play sounds without user interaction.

  • The crash seems to occur when the user resumes the app after some time.

  • Sentry.io breadcrumbs show the app has been running for 45m+, the app is backgrounded (it runs a background service for GPS capture) and then some time later the user resumes the app. App CreateWindow is invoked and because we are resuming I've been advised to return back the same existing Window object rather than create a new one (Android goes ANR otherwise). The LoneWorkingPage PageAppearing method is logged 53ms before the Exception which causes a crash is raised System.ObjectDisposedException: ObjectDisposed_Generic ObjectDisposed_ObjectName_Name, CommunityToolkit.Maui.Core.Views.MauiMediaElement

Permissions:

•	I initially missed adding permissions to the manifest, but it worked on test devices without them. Since encountering the crash, I’ve added the following permissions as a test, but I’m unsure if they’re necessary for local audio playback and am hesitant to request unnecessary permissions:

Additional Settings:

  • I’ve also added ResizeableActivity = true but am unsure if this impacts the issue.

Expected Behavior:

  • Sound should play without interaction and without crashes after resuming the app.

Observed Behavior:

  • App crashes when resuming the app and the LoneWorkingPage is navigated to.

Steps to Reproduce:

1.	Open `LoneWorkingPage` with MediaElement for audio playback.
2.	Run the app as a background service
3.	Observe crash upon resumption of the app which navigated back to the `LoneWorkingPage`

Exception Stack Trace: (condensed for readability)

Exception android.runtime.JavaProxyThrowable: [System.ObjectDisposedException]: ObjectDisposed_Generic
ObjectDisposed_ObjectName_Name, CommunityToolkit.Maui.Core.Views.MauiMediaElement
  at Java.Interop.JniPeerMembers.AssertSelf + 0x29
  at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeVirtualVoidMethod + 0x0
  at Android.Views.ViewGroup.RemoveView + 0x31
  at Microsoft.Maui.WindowOverlay.DeinitializePlatformDependencies + 0x3f
  at Microsoft.Maui.WindowOverlay.Deinitialize + 0x0
  at Microsoft.Maui.VisualDiagnosticsOverlay.Deinitialize + 0x18
  at Microsoft.Maui.Handlers.WindowHandler.OnRootViewChanged + 0x43
  at Microsoft.Maui.Platform.NavigationRootManager.OnWindowContentPlatformViewCreated + 0xa
  at Microsoft.Maui.Platform.NavigationRootManager+ElementBasedFragment.OnViewCreated + 0xe
  at AndroidX.Fragment.App.Fragment.n_OnViewCreated_Landroid_view_View_Landroid_os_Bundle_ + 0x17
  at Android.Runtime.JNINativeWrapper.Wrap_JniMarshal_PPLL_V + 0x5
  at crc6452ffdc5b34af3a0f.NavigationRootManager_ElementBasedFragment.n_onViewCreated
  at crc6452ffdc5b34af3a0f.NavigationRootManager_ElementBasedFragment.onViewCreated (NavigationRootManager_ElementBasedFragment.java:36)
  at androidx.fragment.app.Fragment.performViewCreated (Fragment.java:3152)
  at androidx.fragment.app.FragmentStateManager.createView (FragmentStateManager.java:608)
  at androidx.fragment.app.FragmentStateManager.moveToExpectedState (FragmentStateManager.java:286)
  at androidx.fragment.app.FragmentManager.executeOpsTogether (FragmentManager.java:2164)
  at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute (FragmentManager.java:2065)
  at androidx.fragment.app.FragmentManager.execPendingActions (FragmentManager.java:2002)
  at androidx.fragment.app.FragmentManager.dispatchStateChange (FragmentManager.java:3277)
  at androidx.fragment.app.FragmentManager.dispatchActivityCreated (FragmentManager.java:3187)
  at androidx.fragment.app.FragmentController.dispatchActivityCreated (FragmentController.java:263)
  at androidx.fragment.app.FragmentActivity.onStart (FragmentActivity.java:350)
  at androidx.appcompat.app.AppCompatActivity.onStart (AppCompatActivity.java:251)
  at android.app.Instrumentation.callActivityOnStart (Instrumentation.java:1470)
  at android.app.Activity.performStart (Activity.java:8170)
  at android.app.ActivityThread.handleStartActivity (ActivityThread.java:3806)
  at android.app.servertransaction.TransactionExecutor.performLifecycleSequence (TransactionExecutor.java:221)
  at android.app.servertransaction.TransactionExecutor.cycleToPath (TransactionExecutor.java:201)
  at android.app.servertransaction.TransactionExecutor.executeLifecycleState (TransactionExecutor.java:173)
  at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:97)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2348)
  at android.os.Handler.dispatchMessage (Handler.java:106)
  at android.os.Looper.loopOnce (Looper.java:233)
  at android.os.Looper.loop (Looper.java:344)
  at android.app.ActivityThread.main (ActivityThread.java:8191)
  at java.lang.reflect.Method.invoke
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:584)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1034)

Could you advise if the permissions and ResizeableActivity setting are essential here (for local sounds only), or if there’s another approach to ensure stability with MediaElement in this scenario?

Here's an example of my XAML (same in both views)

<toolkit:MediaElement x:Name="mediaElementControlInXaml" HandlerProperties.DisconnectPolicy="Manual" ShouldAutoPlay="false" IsVisible="false"/>

I then reference that in my ViewModel to play a sound.

When the app is running as a background service the MAUI Window and my associated View and ViewModels are still instantiated, so I'd like to ensure the MediaElement doesn't lose it's native reference when backgrounded/resumed.

Kind Regards,

Rob.

RobbiewOnline avatar Nov 08 '24 10:11 RobbiewOnline

I'm having a similar experience with MediaElement 4.1.2. In my case, AppShell has a TabBar instead of a ShellContent. The TabBar navigates to a home page, settings page and browse page. The browse page has some navigation to from a main group to a subgroup to an item detail page. If, after browsing to and playing a clip, the user selects the main tab or settings tab and then attempts to go back to the browse tab, I get cannot access a disposed object error. If I put the calls to mediaElement.Handler?.DisconnectHandler(); in either OnDisappearing() or Unloaded() I get System.ObjectDisposedException: 'Cannot access a disposed object. Object name: 'CommunityToolkit.Maui.Core.Views.MauiMediaElement'.' on that DicsonnectHandler() call.

mjmeans avatar Dec 18 '24 01:12 mjmeans

If you can test against this PR: https://github.com/CommunityToolkit/Maui/pull/2076 and report if it solves your issue I would appreciate it.

ne0rrmatrix avatar Dec 18 '24 04:12 ne0rrmatrix

I had been trying many things over the last several days. Probably 20 hours experimenting and researching this one issue before I decided to post here. I was really worried that I was spending way too much time on something that was simple to do in the old Xamarin from 4 years ago, though at that time I was only targeting Android.

After posting here I also discovered that MediaElement requires that it be part of the visual tree to work at all; even when only playing audio clips. I found this tidbit of information by removing the XAML MediaElement and adding the control and bindings in the page's class constructor. This idea was that I could manage the control's disposal manually and later move it to a Service class. However, if I commented out the Controls.Add(mediaElement); it would not play anything at all. Thus, eliminating the possibility of moving it to a Service class.

I have no need for player controls or visual elements just to play sound effects. So, I started looking for some other way to do what I need. So, I just tried Plugin.Maui.Audio for the first time. It is working fine so far on Android. Tested for a couple of hours now with no issues. Still have to do some profiling and look for memory leaks, etc. I don't yet have an iOS device to play with yet either. If it turns out that this other package has issues with iOS or I have to go back to the drawing board for another reason, I'll return here. If after tomorrows testing my app is fine, then it means it's almost finished, and I could get it in the app stores before Xmas.

I'm leery of trying to use an unreleased library version in an app I intend to publish. However, I will have to come back to this if the other package, which is working fine up to now, actually has other issues. Beyond that, I can possibly test this PR if I end up meeting my deadline and have some free time. I'm sorry I can't give you a better answer at this time,

mjmeans avatar Dec 18 '24 09:12 mjmeans

@mjmeans if you only need to play sound effects I would encourage you to use Plugin.Maui.Media. If there are issues with it then please feed them back on its repo. I help maintain that package too so we can work towards fixing things 😃

bijington avatar Dec 18 '24 09:12 bijington

I did brieffly look at the PR. there is quite a lot of commits there. Too much to digest in a few minutes. One thing I noticed is that it's on version 8, which I think is a good thing. Greater compatibility with older devices and is on the long-term service branch, whereas .NET 9.0 is not. I'll look into your other repo in a few days to see what it can do.

mjmeans avatar Dec 18 '24 09:12 mjmeans

Can you check and see if this PR fixes your issue? #2076 If it does not can you get back to me.

We are starting to see the Dispose Exception again, everytime we play a video, dispose it and then set the App.Mainpage, then we hit this. I tried your Media3 branch, but its the same.

Pmr-precure avatar Dec 19 '24 11:12 Pmr-precure

Hi, I am updating my MAUI App to Net9 and the Toolkit:MediaElement is crashing every time System.ObjectDisposedException: Cannot access a disposed object. Object name: 'CommunityToolkit.Maui.Core.Views.MauiMediaElement' even without playing a video. When I set the new MainPage the app crashes.

jhovelnu avatar Dec 19 '24 13:12 jhovelnu

The .NET MAUI team re-engineered Handler disconnection in .NET 9: https://learn.microsoft.com/en-us/dotnet/maui/whats-new/dotnet-9?view=net-maui-9.0#handler-disconnection

If you are manually disconnecting the Handler, you need to first set HandlerProperties.SetDisconnectPolicy(video, HandlerDisconnectPolicy.Manual);.

TheCodeTraveler avatar Dec 19 '24 18:12 TheCodeTraveler

The .NET MAUI team re-engineered Handler disconnection in .NET 9: https://learn.microsoft.com/en-us/dotnet/maui/whats-new/dotnet-9?view=net-maui-9.0#handler-disconnection

If you are manually disconnecting the Handler, you need to first set HandlerProperties.SetDisconnectPolicy(video, HandlerDisconnectPolicy.Manual);.

Will try this tomorrow

Pmr-precure avatar Dec 19 '24 18:12 Pmr-precure

The .NET MAUI team re-engineered Handler disconnection in .NET 9: https://learn.microsoft.com/en-us/dotnet/maui/whats-new/dotnet-9?view=net-maui-9.0#handler-disconnection

If you are manually disconnecting the Handler, you need to first set HandlerProperties.SetDisconnectPolicy(video, HandlerDisconnectPolicy.Manual);.

Hi, I added the HandlerProperties.SetDisconnectPolicy in the OnAppearing and now it works well, the app does not crash anymore.

Image

Image

jhovelnu avatar Dec 19 '24 19:12 jhovelnu

The .NET MAUI team re-engineered Handler disconnection in .NET 9: https://learn.microsoft.com/en-us/dotnet/maui/whats-new/dotnet-9?view=net-maui-9.0#handler-disconnection

If you are manually disconnecting the Handler, you need to first set HandlerProperties.SetDisconnectPolicy(video, HandlerDisconnectPolicy.Manual);.

No crashes now :D weee.

Pmr-precure avatar Dec 20 '24 08:12 Pmr-precure