jamesmontemagno / MediaPlugin

Take & Pick Photos and Video Plugin for Xamarin and Windows
MIT License
712 stars 357 forks source link

Only one operation can be active at at time #598

Open Eliezer10 opened 6 years ago

Eliezer10 commented 6 years ago

public async void Agregar_Clicked(object sender, EventArgs e) {

 var cameraStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Camera);
 var storageStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);

  if (cameraStatus != PermissionStatus.Granted || storageStatus != PermissionStatus.Granted)
        {
  var results = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Camera, Permission.Storage });
            cameraStatus = results[Permission.Camera];
            storageStatus = results[Permission.Storage];
        }

        if (cameraStatus == PermissionStatus.Granted && storageStatus == PermissionStatus.Granted)
        {
            var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
            {
                Directory = "Sample",
                Name = "test.jpg"
            });
        }
        else
        {
            await DisplayAlert("Permissions Denied", "Unable to take photos.", "OK");

            CrossPermissions.Current.OpenAppSettings();
        }

    }
ronnyhash commented 6 years ago

I noticed this error as well in an App Center crash log. It happens when the user taps twice on the button to take the picture.

I tried wrapping the call in a try/catch block but the app still crashes. It would be great if it handled the situation, without crashing the app.

Here's the error:

MediaImplementation.TakeMediaAsync (System.String type, System.String action, Plugin.Media.Abstractions.StoreMediaOptions options) System.InvalidOperationException: Only one operation can be active at a time

Here's the stack trace:

MediaImplementation.TakeMediaAsync (System.String type, System.String action, Plugin.Media.Abstractions.StoreMediaOptions options) MediaImplementation+d17.MoveNext () ExceptionDispatchInfo.Throw () TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) TaskAwaiter`1[TResult].GetResult () RouteStopPage+d103.MoveNext () ExceptionDispatchInfo.Throw () AsyncMethodBuilderCore+<>c.b6_0 (System.Object state) SyncContext+<>c__DisplayClass2_0.b0 () Thread+RunnableImplementor.Run () IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this) (wrapper dynamic-method) System.Object.5adf53a8-3fdf-4554-aef0-4c87800b2a0a(intptr,intptr)

Eliezer10 commented 6 years ago

I still can not fix it :(

scastria commented 6 years ago

This bug is hitting us too but with a different workflow:

  1. Launch app
  2. start media picker
  3. click home button
  4. resume app by clicking icon on phone desktop (if you use the task switcher, it works)
  5. app resumes but media picker is gone
  6. start media picker
  7. crash with "Only one operation can be active at at time"

The cause is pretty simple. The media picker uses TaskCompletionSource to turn a callback driven API into Task async/await style. but the code adds a check to make sure that only 1 TaskCompletionSource is active at one time. Each usage of the media picker does the following:

  1. Create TaskCompletionSource
  2. Verify that a previous TaskCompletionSource is null, throw exception if NOT null
  3. setup media picker and register a handler when user picks/takes a photo
  4. after user picks/takes a photo, the handler is called which sets the TaskCompletionSource back to null so that it is ready for next usage

So in my workflow of clicking the Home button in the middle of picking a photo, the user never picked/took a photo so the handler is never called to null out the TaskCompletionSource. By resuming the app using the phone desktop icon, the media picker is lost so when the user tries to launch the media picker a second time, it fails the null check in step 2 above causing an exception to be thrown.

So whether you click the button twice or do my workflow, in both cases TaskCompletionSource is not null the second time and the exception is thrown.

This needs to be fixed.

pfaucon commented 6 years ago

I'm not sure why but I don't see this issue in our production app (was using 4.0.1.1 but also tested upgrading to 4.0.1.5).

I did see this issue when re-implementing the image multi-select branch though, the fix I implemented is here, you only need the changes in src/Media.Plugin/iOS/ECLImagePickerViewController.cs. Essentially if you tap outside the modal sometimes the modal is dismissed without hitting the other dismiss paths, I just added on more check when the VC is dismissed. If you need a quick fix you could try building that nuget locally and using it until it gets pulled into master.

MarnusStoop commented 5 years ago

I am experiencing this issue as well, are there any plans on fixing this or has anyone found a workaround

vagrawal1986 commented 5 years ago

I'm not sure why but I don't see this issue in our production app (was using 4.0.1.1 but also tested upgrading to 4.0.1.5).

I am hitting this issue on droid ONLY. can be easily reproduced by following the steps - https://github.com/jamesmontemagno/MediaPlugin/issues/598#issuecomment-412937648

kkarakk commented 5 years ago

i hit this issue when i was launching photo camera intent twice accidentally(fast button presses in emulator). once i debounced the button,the issue went away. library doesn't like it when two photo intents are being called i think

Trevonious commented 5 years ago

I am seeing this issue, on the new beta build, which includes the Multi-Select feature. On iOS, clicking outside the popup dismisses it, but the next time you try to launch the Gallery select, you get a popup messages that says "Only one operation can be active at at time." On Android, when the gallery select displays (fullscreen) clicking the onscreen back button or the hardware back button both result in a null exception from the PickPhotosAsync call.

vibhatt commented 4 years ago

I am seeing this issue on the latest version of Media plugin when the user presses home button on iOS.

brzezinol commented 4 years ago

I see such error on AppCenter, but I cannot reproduce this problem on my devices and emulators. Mentioned method https://github.com/jamesmontemagno/MediaPlugin/issues/598#issuecomment-412937648 not work for me. I use button debouncing. Does somebody know any other solution for reproduce this bug? ----------Edit Bug appear on release version. Not on debug.

Nullstr1ng commented 4 years ago

Hi James. I am getting this error "Only one operation can be active at a time'" and my project is using the latest version.

image

Here's the actual thing
temp05092020-190537

thinking ..

should this CrossMedia.Current.Initialize(); be called at startup?

Nullstr1ng commented 4 years ago

workaround

from

ctor {
    o.Event += async (s,e) => {
        await CrossMedia.Current.Initialize();
        var file = await CrossMedia.Current.TakePhotoAsync(~~~~~
    }
}

to

ctor {
    var t = Task.Run(async () => { await CrossMedia.Current.Initialize(); });
    t.Wait();

    o.Event += TheEvent;
}

async void TheEvent(s, e) {
    var file = await CrossMedia.Current.TakePhotoAsync(~~~~~
}

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

    o.Event -= TheEvent;
}
samir05051994 commented 4 years ago

no need of any workaround

to this in your MainActivity

" LaunchMode = LaunchMode.SingleTop"

example : [Activity(Label = "MyApp", Theme = "@style/splashscreen", Icon = "@mipmap/icon",MainLauncher =true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, LaunchMode = LaunchMode.SingleTop,NoHistory =false, ScreenOrientation = ScreenOrientation.Portrait)]

RhomGit commented 3 years ago

My users are reporting this also.

While adding photos, in some cases rather than going back to the activity screen, the screen goes white and app locks up. In other cases the app returns to the home screen and progress on the activity is lost. I was briefly able to recreate the issue on my phone when uploading items from my gallery, but the issue is intermittent.

image

I will be trying the workaround suggested by @Nullstr1ng , thanks.

deli-nik commented 3 years ago

While adding photos, in some cases rather than going back to the activity screen, the screen goes white and app locks up. In other cases the app returns to the home screen and progress on the activity is lost. I was briefly able to recreate the issue on my phone when uploading items from my gallery, but the issue is intermittent.

@RhomGit I notice this only happens to my users if they use Samsung Gallery/Camera to pick/take photos. After they switch the default camera/picker app, this issue doesn't happen anymore.

I don't know what to make of this. I guess the library should still handle this problem as we can't ask all our users to change their default apps, but don't really know the root cause in order to debug effectively.

RhomGit commented 3 years ago

Ok, after doing a little reading it seems that this plugin is now archived and seeking a maintainer so I don't think we can expect a fix any time soon. Ref: https://github.com/jamesmontemagno/MediaPlugin/issues/903 @jamesmontemagno ^ you should probably pin that topic?

The recommendation is to migrate to Xamarin.Essentials MediaPicker however it is lacking some important features (and thus not a replacement for this plugin yet): https://github.com/xamarin/Essentials/issues/1640

I also noticed that the comment here https://github.com/xamarin/Essentials/issues/1410#issuecomment-723646695 mentions "On Android you just have to insert the EXTRA_ALLOW_MULTIPLE to the intent. However some apps like the Samsung Gallery ignore it". @nikadli I wonder if the two issues are related? It is interesting to note your observation though, thanks for that. And ... no, I won't be able to recommended to our user base to change their default camera/picker app lol.

deli-nik commented 3 years ago

@RhomGit yup, I read somewhere in one of similar issues comments that this same issue still exists in Xamarin Essentials Media Picker 1.6. And like you said, it's not a replacement for this plugin yet. But if this issue is fixed there, eventually I think I will migrate to Xamarin Essentials anyway.

That comment is interesting, most likely that's why only Samsung Gallery encounter this problem. Thanks to your clue about the intent, I found this - https://stackoverflow.com/questions/51780105/picking-multiple-images-on-clicking-from-gallery. Looks like there's a way to force insert that intent. Except it's not immediately clear how to do that in Xamarin Forms. Probably have to do this in platform-specific project.

deli-nik commented 3 years ago

And ... no, I won't be able to recommended to our user base to change their default camera/picker app lol.

Also on this, they dont really have to change default. If the OS prompts to choose which apps to use, just don't choose Samsung apps. But this is less than ideal of course.