CommunityToolkit / Maui

The .NET MAUI Community Toolkit is a community-created library that contains .NET MAUI Extensions, Advanced UI/UX Controls, and Behaviors to help make your life as a .NET MAUI developer easier
https://learn.microsoft.com/dotnet/communitytoolkit/maui
MIT License
2.28k stars 403 forks source link

[BUG] - MediaElement DisconnectHandler Crash Android App #2195

Open jhovelnu opened 2 months ago

jhovelnu commented 2 months ago

Is there an existing issue for this?

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

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 commented 2 months ago

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_osBundle(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)

ne0rrmatrix commented 2 months ago

That repository does not exist

jhovelnu commented 2 months ago

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

ne0rrmatrix commented 2 months ago

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,.

jhovelnu commented 2 months ago

@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.

Pmr-precure commented 2 months ago

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 commented 2 months ago

@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 commented 2 months ago

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.

ne0rrmatrix commented 2 months ago

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

Pmr-precure commented 2 months ago

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 commented 2 months ago

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 commented 2 months ago

@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.

ne0rrmatrix commented 2 months ago

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.

Pmr-precure commented 2 months ago

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 commented 2 months ago

@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.

ne0rrmatrix commented 2 months ago

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.

jhovelnu commented 1 month ago

@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

ne0rrmatrix commented 1 month ago

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.

RobbiewOnline commented 2 weeks ago

Hi,

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

Environment:

Usage Details:

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.