Android条码扫描相机覆盖,按钮切换相机

时间:2017-04-06 06:27:53

标签: android camera overlay barcode-scanner

在我的应用程序中,我有条形码扫描块的视图,它会触发相机通过自定义插件扫描条形码。

我在相机覆盖层上添加了2个按钮。毋庸置疑,我已阅读并尝试了此论坛的各种建议。但无法解决问题。

  • 停止:要停止扫描,请关闭相机并返回应用程序的主视图。
  • 翻转(相机切换):单击时,应更改设备的相机。 但是,我的应用程序一直在崩溃。

我做错了什么?

import me.dm7.barcodescanner.zxing.ZXingScannerView;
import android.hardware.Camera;

public class FloatingScannerFragment extends Fragment implements ZXingScannerView.ResultHandler{

private static final String FLASH_STATE = "FLASH_STATE";
private static final String AUTO_FOCUS_STATE = "AUTO_FOCUS_STATE";
private static final String SELECTED_FORMATS = "SELECTED_FORMATS";
private static final String CAMERA_ID = "CAMERA_ID";
private ZXingScannerView mScannerView;
private boolean mFlash=false;
private boolean mAutoFocus=true;
private ArrayList<Integer> mSelectedIndices;
private int mCameraId = -1;
private FloatingScannerFragmentCallbacks mFragmentCallbacks;
private double x, y, w, h;
Button buttonStop, buttonFlipCamera;
private Camera mCamera;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) {
    if(state == null){
        state = this.getArguments();
    }
    if(state != null) {
        x = state.getDouble("x");
        y = state.getDouble("y");
        w = state.getDouble("w");
        h = state.getDouble("h");
    }

    mScannerView = new ZXingScannerView(getActivity()){
        //Adding STOP and CameraFlip buttons on camera Overlay
        @Override
        public void setupCameraPreview(CameraWrapper cameraWrapper) {
            super.setupCameraPreview(cameraWrapper);
            buttonStop = new Button(getActivity());
            buttonStop.setText("STOP");
            buttonFlipCamera = new Button(getActivity());
            buttonFlipCamera.setText("FLIP");

            //For buttons visibility, set the layout params in order to give some width and height:
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            buttonStop.setLayoutParams(params);
            this.addView(buttonStop);
            buttonFlipCamera.setX((float) x + buttonStop.getLayoutParams().height);
            buttonFlipCamera.setY((float) y + buttonStop.getLayoutParams().height);
            buttonFlipCamera.setLayoutParams(new ViewGroup.LayoutParams((buttonStop.getLayoutParams().width),(buttonStop.getLayoutParams().height)));
            this.addView(buttonFlipCamera);

            buttonStop.setOnClickListener( new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mScannerView.stopCamera();
                    mScannerView.removeAllViews();
                }
            });

            buttonFlipCamera.setOnClickListener( new OnClickListener() {
                @Override
                public void onClick(View v) {
                   switchCamera();
                }

            });
        }

        @Override
        protected IViewFinder createViewFinderView(Context context) {
            return new CustomViewFinderView(context);
        }

    };

    mScannerView.setZ(10);
    mScannerView.setAutoFocus(true);
    mScannerView.setFlash(false);
    mScannerView.setX((float) x);
    mScannerView.setY((float) y);
    mScannerView.setLayoutParams(new ViewGroup.LayoutParams((int)w, (int)h));

    return mScannerView;
}

public void setCallback(FloatingScannerFragmentCallbacks fragmentCallbacks){
    mFragmentCallbacks = fragmentCallbacks;
}

@Override
public void onResume() {
    super.onResume();
    mScannerView.setResultHandler(this);
    mScannerView.startCamera(mCameraId);
    mScannerView.setFlash(mFlash);
    mScannerView.setAutoFocus(mAutoFocus);
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putBoolean(FLASH_STATE, mFlash);
    outState.putBoolean(AUTO_FOCUS_STATE,mAutoFocus);

}

@Override
public void onHiddenChanged(boolean hidden) {
    super.onHiddenChanged(hidden);
    if(!hidden) mScannerView.resumeCameraPreview(this);
}

@Override
public void onPause() {
    super.onPause();
    mScannerView.stopCamera();
}
/**
 * switches between main and front camera
 */
private void switchCamera() {
    // TODO: check the number of available cameras
    mScannerView.stopCamera();
    if (mCameraId == -1) {
        mCameraId = 0;
    } else {
        mCameraId = -1;
    }
    mScannerView.startCamera(mCameraId);
    }
//For the custom text
private static class CustomViewFinderView extends ViewFinderView {
    public static final String TRADE_MARK_TEXT = "Please place barcode inside box";
    public static final int TRADE_MARK_TEXT_SIZE_SP = 12;
    public final Paint PAINT = new Paint();

    public CustomViewFinderView(Context context) {
        super(context);
        init();
    }

    public CustomViewFinderView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        PAINT.setColor(Color.WHITE);
        PAINT.setAntiAlias(true);
        float textPixelSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
            TRADE_MARK_TEXT_SIZE_SP, getResources().getDisplayMetrics());
        PAINT.setTextSize(textPixelSize);
        setSquareViewFinder(true);
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawTradeMark(canvas);
    }

    private void drawTradeMark(Canvas canvas) {
        Rect framingRect = getFramingRect();
        float tradeMarkTop;
        float tradeMarkLeft;
        if (framingRect != null) {
            tradeMarkTop = framingRect.bottom + PAINT.getTextSize() + 10;
            tradeMarkLeft = framingRect.left;
        } else {
            tradeMarkTop = 10;
            tradeMarkLeft = canvas.getHeight() - PAINT.getTextSize() - 10;
        }
        canvas.drawText(TRADE_MARK_TEXT, tradeMarkLeft, tradeMarkTop, PAINT);
    }
}
}

我的Handleresult():理想情况下,在第一次扫描没有恢复后也应恢复相机。

 @Override
public void handleResult(Result rawResult) {
    try {
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r = RingtoneManager.getRingtone(getActivity().getApplicationContext(), notification);
        r.play();
    } catch (Exception e) {}
    mFragmentCallbacks.onBarcodeScanned(rawResult.getText());

    //Resume scanning
    mScannerView.resumeCameraPreview(this);
    }

感谢您的所有帮助。

编辑: Logcat信息:

04-06 10:16:56.642 2130-3378/com.google.android.googlequicksearchbox:search 
I/MicroRecognitionRunner: Starting detection.
04-06 10:16:56.644 2130-2237/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_starting com.google.android.apps.gsa.staticplugins.z.c@e64e47b
04-06 10:16:56.648 1307-1643/? W/APM_AudioPolicyManager: getInputForAttr() failed opening input: samplingRate 16000, format 1, channelMask 10
04-06 10:16:56.648 2130-2237/com.google.android.googlequicksearchbox:search E/AudioRecord: Could not get audio input for session 393, record source 1999, sample rate 16000, format 0x1, channel mask 0x10, flags 0
04-06 10:16:56.653 2130-2237/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -22.
04-06 10:16:56.654 2130-2237/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
04-06 10:16:56.654 2130-2237/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_started com.google.android.apps.gsa.staticplugins.z.c@e64e47b
04-06 10:16:56.655 2559-3373/com.google.android.gms W/PlatformStatsUtil: Could not retrieve Usage & Diagnostics setting. Giving up.
04-06 10:16:56.657 2130-2237/com.google.android.googlequicksearchbox:search E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.recorded
04-06 10:16:56.658 2130-2130/com.google.android.googlequicksearchbox:search I/MicroDetectionWorker: onReady
04-06 10:16:56.723 2130-2237/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_close com.google.android.apps.gsa.staticplugins.z.c@e64e47b
04-06 10:16:56.735 2130-3378/com.google.android.googlequicksearchbox:search I/MicroRecognitionRunner: Detection finished
04-06 10:16:56.735 2130-3378/com.google.android.googlequicksearchbox:search W/ErrorReporter: reportError [type: 211, code: 524300]: Error reading from input stream
04-06 10:16:56.739 2130-2308/com.google.android.googlequicksearchbox:search I/MicroRecognitionRunner: Stopping hotword detection.
04-06 10:16:56.740 2130-3378/com.google.android.googlequicksearchbox:search W/ErrorProcessor: onFatalError, processing error from engine(4)                                                                                     
com.google.android.apps.gsa.shared.speech.a.g: Error reading from input stream                                                                                         
at 
com.google.android.apps.gsa.staticplugins.recognizer.i.a.a(SourceFile:342)                                                                                    
at com.google.android.apps.gsa.staticplugins.recognizer.i.a$1.run(SourceFile:1367)                                                                                         
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)                                                                                          
at java.util.concurrent.FutureTask.run(FutureTask.java:237)                                                                                      
at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)                                                                                             
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)                                                                                        
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)                                                                                            
at java.lang.Thread.run(Thread.java:761)                                                                                           
at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)                                                                                       
Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.                                                                                            
at com.google.android.apps.gsa.speech.audio.Tee.g(SourceFile:2531)                                                                                          
at com.google.android.apps.gsa.speech.audio.ap.read(SourceFile:555)                                                                                           
at java.io.InputStream.read(InputStream.java:101)                                                                                             
at com.google.android.apps.gsa.speech.audio.al.run(SourceFile:362)                                                                                           
at com.google.android.apps.gsa.speech.audio.ak$1.run(SourceFile:471)                                                                                       
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)                                                                                          
at java.util.concurrent.FutureTask.run(FutureTask.java:237)                                                                                      
at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)                                                                                        
at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)                                                                                            
at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)                                                                                       
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)                                                                                          
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)                                                                                           
at java.lang.Thread.run(Thread.java:761)                                                                                      
at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85) 
04-06 10:16:56.740 2130-3378/com.google.android.googlequicksearchbox:search I/AudioController: internalShutdown
04-06 10:16:56.745 2130-3377/com.google.android.googlequicksearchbox:search I/DeviceStateChecker: DeviceStateChecker cancelled
04-06 10:16:56.748 2130-2130/com.google.android.googlequicksearchbox:search I/MicroDetector: Keeping mic open: false
04-06 10:16:56.748 2130-2130/com.google.android.googlequicksearchbox:search I/MicroDetectionWorker: #onError(false)
04-06 10:16:56.778 1309-3367/? V/EmulatedCamera_CallbackNotifier: enableMessage: msg_type = 0x10
04-06 10:16:56.780 1309-3367/? V/EmulatedCamera_CallbackNotifier:     CAMERA_MSG_PREVIEW_FRAME
04-06 10:16:56.781 1309-3367/? V/EmulatedCamera_CallbackNotifier: **** Currently enabled messages:
04-06 10:16:56.781 1309-3367/? V/EmulatedCamera_CallbackNotifier:     CAMERA_MSG_ERROR
04-06 10:16:56.781 1309-3367/? V/EmulatedCamera_CallbackNotifier:     CAMERA_MSG_FOCUS
04-06 10:16:56.781 1309-3367/? V/EmulatedCamera_CallbackNotifier:     CAMERA_MSG_ZOOM
04-06 10:16:56.781 1309-3367/? V/EmulatedCamera_CallbackNotifier:     CAMERA_MSG_PREVIEW_FRAME
04-06 10:16:56.781 1309-3367/? V/EmulatedCamera_CallbackNotifier:     CAMERA_MSG_PREVIEW_METADATA
04-06 10:16:56.828 1309-3370/? V/EmulatedCamera_CallbackNotifier: disableMessage: msg_type = 0x10
04-06 10:16:56.828 1309-3370/? V/EmulatedCamera_CallbackNotifier:     CAMERA_MSG_PREVIEW_FRAME
04-06 10:16:56.828 1309-3370/? V/EmulatedCamera_CallbackNotifier: **** Currently enabled messages:
04-06 10:16:56.828 1309-3370/? V/EmulatedCamera_CallbackNotifier:     CAMERA_MSG_ERROR
04-06 10:16:56.828 1309-3370/? V/EmulatedCamera_CallbackNotifier:     CAMERA_MSG_FOCUS
04-06 10:16:56.828 1309-3370/? V/EmulatedCamera_CallbackNotifier:     CAMERA_MSG_ZOOM
04-06 10:16:56.828 1309-3370/? V/EmulatedCamera_CallbackNotifier:     CAMERA_MSG_PREVIEW_METADATA

应用程序布局:

BARCODE SCANNING app view

注意:对于那些为了提供反对票而在这里的成员,请求您停止这样做。如果你不能提出你的建议,至少给别人花一些时间,帮助像我这样的人。 作为一个新鲜的开发人员,任何语言都已经充满了压力,但让代码工作的乐趣是神圣的。这是一个过程,需要时间。谢谢!!

编辑2:更改了按钮开关相机的代码。这是翻转相机的正确方法吗? 另外,如果我在扫描后正确使用简历,请提供任何建议吗?

0 个答案:

没有答案