Ouriel Bennathan
Ouriel Bennathan

Reputation: 1

how open front camera in android java

I want to open front camera, this code open camera but not front:

Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePicture.putExtra("android.intent.extras.CAMERA_FACING", 1);
startActivityForResult(takePicture, 1);

Upvotes: 0

Views: 551

Answers (1)

ByteMaster
ByteMaster

Reputation: 21

This code is for launching the camera application and capturing an image, but it's not guaranteed that it will always open the front camera. The line

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

is an attempt to specify that the front camera should be used, but not all camera applications support this extra. To ensure that the front camera is opened, you need to handle the camera access in your own code using the Android Camera API.

I'll share an example right below:

    private Camera camera;
    private int cameraId = 0;
    public void openFrontCamera() {
    
    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) {
            cameraId = i;
            break;
        }
    }    
    camera = Camera.open(cameraId);

Upvotes: 2

Related Questions