Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Camera Black Screen

I am trying create an app that will read a QR Code, This code worked intermittently but it would give Permission errors and would not load. I believe I have those fixed, but now I get a Black Screen. There are no errors so I do not know where to look, but I feel it has something to do with the permissions.

package com.sample.qrcodereadervision.Activity;

import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;

import com.sample.qrcodereadervision.R;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.SparseArray;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.PermissionUtils;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class QRcodeReader extends AppCompatActivity {
    public final String TAG = getClass().getSimpleName();

    private CameraSource cameraSource;
    /** UI Parts : Preview screen */
    private SurfaceView cameraView;
    /** UI Parts : decoding results */
    private TextView barcodeInfo;

    private static final int REQUEST_CAMERA = 0x00000011;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("QRcodeReader", "onCreate");
        setContentView(R.layout.activity_main);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            requestCameraPermission();
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart");
        barcodeInfo = (TextView) findViewById(R.id.code_info);
        cameraView = (SurfaceView) findViewById(R.id.camera_view);
        startQRcodeReader();
//        startCameraSource();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
    }

    //@Override
    //public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    //    Log.d(TAG, "onRequestPermissionsResult");
    //    QRcodeReaderPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    //}

    private void startQRcodeReader() {
        Log.d(TAG, "startQRcodeReader");
        BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(this)
                .setBarcodeFormats(Barcode.QR_CODE)
                .build();

        cameraSource = new CameraSource
                .Builder(this, barcodeDetector)
                .setAutoFocusEnabled(true)
                .build();

        QRcodeReaderPermissionsDispatcher.startCameraSourceWithCheck(QRcodeReader.this);
        //requestCameraPermission();

        //QR Code reading
        barcodeDetector.setProcessor(
                new Detector.Processor<Barcode>() {
                    @Override
                    public void release() {
                    }

                    @Override
                    public void receiveDetections(Detector.Detections<Barcode> detections) {
                        final SparseArray<Barcode> barcodes = detections.getDetectedItems();
                        if (barcodes.size() != 0) {
                            barcodeInfo.post(
                                    new Runnable() {
                                        public void run() {
                                            barcodeInfo.setText(
                                                    barcodes.valueAt(0).displayValue
                                            );
                                        }
                                    });
                        }
                    }
                });
    }

    @NeedsPermission(Manifest.permission.CAMERA)
    void startCameraSource() {
        Log.d(TAG, "startCameraSource");
        Toast.makeText(this, "\n" +
                "Start the camera source", Toast.LENGTH_SHORT)
                .show();
        try {
            releaseCameraAndPreview();
            if (cameraSource != null) {
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    cameraSource.start(cameraView.getHolder());
                    return;
                }

            }
        } catch (IOException | SecurityException e) {
            Log.w(TAG, e);
        }
    }


    @SuppressWarnings("unused")
    @OnPermissionDenied(Manifest.permission.CAMERA)
    void deniedPermission() {
        Log.d(TAG, "deniedPermission");
        if (PermissionUtils.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
            Toast.makeText(this, "\n" +
                    "It failed to camera startup .", Toast.LENGTH_SHORT)
                    .show();
        }
    }

    @SuppressWarnings("unused")
    @OnShowRationale(Manifest.permission.CALL_PHONE)
    void showRationalForStorage(final PermissionRequest request) {
        Log.d(TAG, "showRationalForStorage");
        Toast.makeText(this, "\n" +
                "The camera of the use permit is required", Toast.LENGTH_SHORT)
                .show();
        request.proceed();
    }

    private void releaseCameraAndPreview() {
        if (cameraSource != null) {
            cameraSource.release();
            cameraSource = null;
        }
    }

    private void requestCameraPermission() {
        Log.i(TAG, "CAMERA permission has NOT been granted. Requesting permission.");

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.CAMERA)) {
            Log.i(TAG,
                    "Displaying camera permission rationale to provide additional context.");
            Snackbar.make(findViewById(R.id.code_info), R.string.permission_camera_rationale,
                    Snackbar.LENGTH_INDEFINITE)
                    .setAction(R.string.ok, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            ActivityCompat.requestPermissions(QRcodeReader.this,
                                    new String[]{Manifest.permission.CAMERA},
                                    REQUEST_CAMERA);
                        }
                    })
                    .show();
        } else {

            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
                    REQUEST_CAMERA);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
        @NonNull int[] grantResults) {
        Log.d(TAG, "onRequestPermissionsResult");
        switch (requestCode) {
            case REQUEST_CAMERA: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    QRcodeReaderPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
                    startCameraSource();

                } else {

                    finish();
                }
            }
            break;
        }
    }

}

The Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sample.qrcodereadervision">

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus"/>

    <application
        android:theme="@style/AppTheme"
        android:label="@string/app_name"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:supportsRtl="true">

        <activity android:name=".Activity.QRcodeReader">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <meta-data android:name="com.google.android.gms.vision.DEPENDENCIES" android:value="barcode"/>
    </application>

</manifest>
like image 744
Sobo Avatar asked Jul 22 '16 13:07

Sobo


1 Answers

pretty late for it but it will help you.

After that you have setup your camera and added preview and everything else. Just call

recreate();

Usage example in your Camera Activity like this.

    camera = prepareCamera(camera); // a method to get camera instance
    preview = createCameraPreview(camera) // a method which returns object of surfaceview
    showCameraPreview(preview); // adding preview to the frame
    recreate();   // <---This line should be called every time we setup a camera preview 
like image 172
Divyanshu Kumar Avatar answered Oct 18 '22 22:10

Divyanshu Kumar