我有一个奇怪的例外。我在一个页面中使用了PhoneCamera API,用户可以制作一些照片,拍摄后直接上传。
我的代码:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
_mediaLibrary = new MediaLibrary();
// Initialize the camera object
_phoneCamera = new PhotoCamera(CameraType.Primary);
_phoneCamera.Initialized += CamInitialized;
_phoneCamera.AutoFocusCompleted += PhoneCamera_AutoFocusCompleted;
_phoneCamera.CaptureImageAvailable += PhoneCamera_CaptureImageAvailable;
// Display the camera feed in the UI
ViewfinderBrush.SetSource(_phoneCamera);
// Rotation for transform
ViewfinderTransform.Rotation = _phoneCamera.Orientation;
}
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
if (_phoneCamera != null)
{
// Cleanup
_phoneCamera.Dispose();
_phoneCamera.Initialized -= CamInitialized;
_phoneCamera.AutoFocusCompleted -= PhoneCamera_AutoFocusCompleted;
_phoneCamera.CaptureImageAvailable -= PhoneCamera_CaptureImageAvailable;
if (_cameraInizialized)
{
CameraButtons.ShutterKeyHalfPressed -= CameraButtons_ShutterKeyHalfPressed;
CameraButtons.ShutterKeyPressed -= CameraButtons_ShutterKeyPressed;
}
}
base.OnNavigatingFrom(e);
}
private void CamInitialized(object sender, CameraOperationCompletedEventArgs e)
{
if (e.Succeeded)
{
// Set flashmode
Dispatcher.BeginInvoke(() => { _phoneCamera.FlashMode = FlashMode.Auto; });
// Subscribe to hardeware-button-events
CameraButtons.ShutterKeyHalfPressed += CameraButtons_ShutterKeyHalfPressed;
CameraButtons.ShutterKeyPressed += CameraButtons_ShutterKeyPressed;
_cameraInizialized = true;
}
else
{
// Show error message
}
}
当初始化事件被触发时,一切正常。但是当用户在相机初始化时点击手机的主页按钮时出现异常。(初始化事件未触发)。
当用户使用返回按钮返回时,发生以下异常:
[Type]:[AggregateException]
[ExceptionMessage]:[One or more errors occurred.]
[StackTrace]:[
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at Microsoft.Devices.Camera.OpenCaptureDevice()
at Microsoft.Devices.Camera.<>c__DisplayClass2.<InitializeVideoSession>b__0()]
[InnerExceptions]:[[[Type]:[InvalidOperationException]
[Message]:[The text associated with this error code could not be found.
Unable to acquire the camera. You can only use this class while in the foreground.]
我尝试了许多其他选择,但没有任何效果。我现在不知道为什么会发生此错误。虽然我知道它发生在哪里,在什么情况下。
欢迎任何帮助。谢谢你。