Android Camera2video使用前置摄像头

时间:2015-11-12 06:23:53

标签: android android-camera

我试图找出如何将here设置为使用前置摄像头。我是Android开发的新手,并试图解决这个问题。

1 个答案:

答案 0 :(得分:0)

此方法查找正面相机是否存在并返回其id(如果不存在,则返回-1)

private int findFrontFacingCamera() {
        int cameraId = -1;
        // Search for the front facing camera
        int numberOfCameras = Camera.getNumberOfCameras();
        for (int i = 0; i < numberOfCameras; i++) {
            Camera.CameraInfo info = new Camera.CameraInfo();
            Camera.getCameraInfo(i, info);
            if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                Log.d("CAMERA", "Camera found");
                cameraId = i;
                break;
            }
        }
        return cameraId;
    }

这种方法将帮助您使用前置摄像头:

private void useFrontFacingCamera() {
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {

            Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG).show();

        } else {
            cameraId = findFrontFacingCamera();
            if (cameraId < 0) {
                 Toast.makeText(this, "No front facing camera found.",Toast.LENGTH_LONG).show();
            } else {

                camera = Camera.open(cameraId);
                camera.unlock();

            }
    }

//in my case i have to use frontal camera to make a scan on a qr code :

    IntentIntegrator scanIntegrator = new IntentIntegrator(this);
    scanIntegrator.setCameraId(cameraId); // <-- use this method to use your camera

    scanIntegrator.initiateScan();
}

重要提示:如果您想在其他活动中使用相机,请不要忘记这些方法:

 @Override
    protected void onPause() {

        if (camera != null) {
            camera.stopPreview();
            camera.release();
            camera = null;
            Log.d("camera", "releaseCamera -- done");
        }
        super.onPause();
    }
    @Override
    protected void onResume() {

        if (camera != null) {

            Camera.open();
            Log.d("camera", "openCamera -- done");
        }

        super.onResume();
    }
    @Override
    protected void onStart() {

        super.onStart();
    }
    @Override
    protected void onStop() {
        super.onStop();
        if (camera != null) {
            camera.stopPreview();
            camera.release();
            camera = null;
            Log.e("camera", "releaseCamera -- done");
        }
    }