我正在开发一个需要二维码扫描功能的Windows Phone 8应用程序,而我使用Zxing库来进行二维码扫描。
在这个应用程序中,一旦扫描完成,我需要返回到前一页。
我使用了以下代码:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
_phoneCamera = new PhotoCamera();
_phoneCamera.Initialized += cam_Initialized;
_phoneCamera.AutoFocusCompleted += _phoneCamera_AutoFocusCompleted;
CameraButtons.ShutterKeyHalfPressed += CameraButtons_ShutterKeyHalfPressed;
viewfinderBrush.SetSource(_phoneCamera);
_scanTimer = new DispatcherTimer();
_scanTimer.Interval = TimeSpan.FromMilliseconds(1500);
_scanTimer.Tick += (o, arg) => ScanForBarcode();
base.OnNavigatedTo(e);
}
protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
{
_scanTimer.Stop();
if (cameraInit)
{
Dispatcher.BeginInvoke(() =>
{
if (_phoneCamera != null)
{
_phoneCamera.CancelFocus();
_phoneCamera.Dispose();
_phoneCamera.Initialized -= cam_Initialized;
_phoneCamera = null;
cameraInit = false;
}
});
}
}
void cam_Initialized(object sender, Microsoft.Devices.CameraOperationCompletedEventArgs e)
{
if (e.Succeeded)
{
cameraInit = true;
this.Dispatcher.BeginInvoke(() =>
{
_phoneCamera.FlashMode = FlashMode.Auto;
_previewBuffer = new WriteableBitmap((int)_phoneCamera.PreviewResolution.Width, (int)_phoneCamera.PreviewResolution.Height);
_barcodeReader = new BarcodeReader();
(int)_phoneCamera.PreviewResolution.Width, (int)_phoneCamera.PreviewResolution.Height, 0, 100);
var supportedBarcodeFormats = new List<BarcodeFormat>();
supportedBarcodeFormats.Add(BarcodeFormat.QR_CODE);
supportedBarcodeFormats.Add(BarcodeFormat.DATA_MATRIX);
_barcodeReader.Options.PossibleFormats = supportedBarcodeFormats;
_barcodeReader.Options.TryHarder = true;
_barcodeReader.ResultFound += _bcReader_ResultFound;
_scanTimer.Start();
});
}
else
{
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Unable to initialize the camera");
});
}
}
void _bcReader_ResultFound(Result obj)
{
Dispatcher.BeginInvoke(() =>
{
VibrateController.Default.Start(TimeSpan.FromMilliseconds(100));
a = obj.Text;
_scanTimer.Stop();
NavigationService.GoBack(); //here I am going back to previos page
});
}
private void ScanForBarcode()
{
_phoneCamera.GetPreviewBufferArgb32(_previewBuffer.Pixels);
_previewBuffer.Invalidate();
_barcodeReader.Decode(_previewBuffer);
}
这段代码本来运行良好,但有时在捕获二维码时会使应用程序挂起。
编辑后:
当我在没有调试模式的情况下运行应用程序时,就会出现这个问题。当应用程序变得无响应时,过一段时间它就会崩溃,但不会显示任何错误消息。
所以,请帮我解决这个问题。谢谢。