Generalkidd
Generalkidd

Reputation: 579

Windows Phone camera crashes app when switching between pages

I'm creating a simple camera app for Windows Phone 8 in C#. On the main view, the camera is already initialized. There is a button on the main view that takes you to a separate settings page. However, when I press the back button to return to the main page with the camera view, the app crashes and I get this exception:

An exception of type 'System.InvalidOperationException' occurred in mscorlib.ni.dll but was not handled in user code

WinRT information: Unable to acquire the camera. You can only use this class while in the foreground.

If there is a handler for this exception, the program may be safely continued.

This is the code I use to switch to the settings page:

private void Button_Click(object sender, RoutedEventArgs e)
    {
        NavigationService.Navigate(new Uri("/settings.xaml", UriKind.Relative));
    }

And on the settings page, I just simply use the back button to return to the main page, which is where the crash happens.

This is the code I use for the camera initialization:

protected override async void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        Size resolution = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back).First();//crashes here
        camera = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, resolution);
        video.SetSource(camera);
        previewTransform.Rotation = camera.SensorRotationInDegrees;
    }

The debugger says the app crashes on the 2nd line in that method.

Upvotes: 0

Views: 556

Answers (1)

Pantelis
Pantelis

Reputation: 2060

You also need to dispose your camera instance. In the page hosting the PhotoCaptureDevice object:

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    base.OnNavigatedFrom(e);
    camera.Dispose();
}

Upvotes: 1

Related Questions