选择前置摄像头

时间:2015-08-06 13:33:15

标签: android android-camera

我使用以下代码拍照:

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            //...
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}

有没有办法选择前置摄像头?

2 个答案:

答案 0 :(得分:4)

你可以试试这个。

takePictureIntent.putExtra("android.intent.extras.CAMERA_FACING", 1);

但并非所有相机应用都支持该标志

答案 1 :(得分:1)

您可以使用Camera.CameraInfo.CAMERA_FACING_FRONT

int cameraCount = 0;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
    Camera.getCameraInfo(camIdx, cameraInfo);
    if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
        try {
            cam = Camera.open(camIdx);
        } catch (RuntimeException e) {
            Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
        }
    }
}

并在AndroidManifest.xml中添加权限

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