Home:ALL Converter>ZXingScannerView Android 6 Camera Permission

ZXingScannerView Android 6 Camera Permission

Ask Time:2015-12-14T20:58:26         Author:feberle

Json Formatter

I'm using ZXingScannerView as a qr-code reader in my Fragment
Now I'm having trouble to get the camera work right with the new Android 6 permissions.

Below API 23 everything works fine.

In my onCreateView method I check if camera permission is granted and otherwise ask for it. The dialog appears and I can grant the permission.

But the camera preview remains black until I change the orientation of my device.

Here's my code:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state){

    mScannerView = new ZXingScannerView(getActivity());

    if (ActivityCompat.checkSelfPermission(getMainActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CAMERA_SCAN_QR);
    } else {
        if(state != null) {
            mFlash = state.getBoolean(FLASH_STATE, false);
            mAutoFocus = state.getBoolean(AUTO_FOCUS_STATE, true);
            mSelectedIndices = state.getIntegerArrayList(SELECTED_FORMATS);
            mCameraId = state.getInt(CAMERA_ID, -1);
        } else {
            mFlash = false;
            mAutoFocus = true;
            mSelectedIndices = null;
            mCameraId = -1;
        }
    }

    return mScannerView;
}


@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == PERMISSION_REQUEST_CAMERA_SCAN_QR && hasPermission(grantResults)) {
        Logger.logInfo("permission granted");
        mScannerView.setResultHandler(this);
        mScannerView.startCamera(mCameraId);
        mScannerView.setFlash(mFlash);
        mScannerView.setAutoFocus(mAutoFocus);
    }
}

private boolean hasPermission(int[] grantResults) {
    return grantResults.length > 0 && grantResults[0] == PERMISSION_REQUEST_CAMERA_SCAN_QR;
}


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

}

Author:feberle,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/34267692/zxingscannerview-android-6-camera-permission
yy