How to fix the camera freezing issue when switching between Apps in a windows store app?

How to fix the camera freezing issue when switching between Apps in a windows store app?

Capturing image or video is very common requirement for any windows store app. Displaying the Camera preview in a app is very easy now a days with the help of MediaCapture class. But this causes an issue where when the user tries to minimize the app or tries to switch some other app in the screen then the user may end up freezing the camera preview.In this post let’s see how to fix the camera freezing issue that occurs when a windows store app gets minimized or switched.

This is just because the MediaCapture’s API interact with the camera hardware. So whenever the application loses focus then the hardware associate with the API gets released immediate.

So when the user tries to switch back the same app he/she sees the camera preview gets Freeze. So we have to reinitialize the camera in order to get the camera preview working.

To solve this problem we have an Event called Window.CoreWindow.VisibilityChanged Event. This event gets triggered whenever the app’s visibility gets changed. Subscribing to this event will let the user know when the app losing its visibility and when it comes in to visibility.

Subscribe the Event in OnNavigatedTo method of the page.


Window.Current.CoreWindow.VisibilityChanged += this.CoreWindowVisibilityChanged;

This event provides VisibilityChangedEventArgs, which has a property called Visible, using this property we will get to know whether the page is visible or not. When the page gets visible then initialize the MediaCapture class, when the page gets out of screen then stop the camera preview.

Must Read :


private async void CoreWindowVisibilityChanged(CoreWindow sender, VisibilityChangedEventArgs args)

{
if(args.Visible)

{

MediaCapture mediaCapture = new MediaCapture();

await mediaCapture.InitializeAsync();

captureElement.Source = mediaCapture;

await mediaCapture.StartPreviewAsync();

}

else

{

await mediaCapture.StopPreviewAsync();

}

}

Hope this post might have helped in solving the camera Freezing issue with windows store apps.

Arun Kumar

Arun kumar Surya Prakash, is a  Developer  Consultant. He  is a Microsoft Certified Solution  Developer  for Store App Development, and a Azure Solution Developer. His core skills is on developing Windows Store App and Cross Platform App development. You can follow him @arunnov04