Android SurfaceView有时会保持黑色

时间:2017-08-30 19:20:47

标签: android surfaceview qr-code

我在我的应用中遇到了一个奇怪的错误。 我使用SurfaceView来允许用户扫描QR码。 有时它按预期工作,但有时SurfaceView仍为黑色。

我已查看过其他帖子,但遗憾的是没有找到相关的帖子。

以下是代码段:

//Called when QR scan is needed
private void tryToScan(){
    final BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(this).setBarcodeFormats(Barcode.QR_CODE).build();
    final CameraSource cameraSource = new CameraSource.Builder(this, barcodeDetector).setRequestedPreviewSize(256, 256).build();
    barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
        @Override
        public void release() {}
        @Override
        public void receiveDetections(Detector.Detections<Barcode> detections) {
            final SparseArray<Barcode> codes = detections.getDetectedItems();
            if (codes.size() > 0) {//if codes detected
                sendQr(codes.valueAt(0).displayValue);//send it
            }
        }
    });
    //Adds SurfaceHolder.Callback to SurfaceHolder of SurfaceView by id R.id.scanQr (valid id)
    ((SurfaceView)findViewById(R.id.scanQr)).getHolder().addCallback(new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            try {
                //Sometimes starts successfully but sometimes stays black
                cameraSource.start(holder);
            } catch (IOException e) {
                e.printStackTrace();
            }catch (SecurityException e){
                askCameraPermission();
            }
        }
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
        public void surfaceDestroyed(SurfaceHolder holder) {
            cameraSource.stop();
        }
    });
}

0 个答案:

没有答案