简体   繁体   中英

Switch Cameras on Android using Camera API

Hello There I am newbiew to Camera API. I am learning it to my own! I just want to switch my cameras back-front and front-back! My device do have both front and back cameras! I am doing this like:


public class CameraFrag extends Fragment {

//Variables
private Camera mCamera;
private CameraPreview mPreview;
private ToggleButton flipCamera;
////////////////////////////////////

public CameraFrag() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //inflate the layout
    View v = inflater.inflate(R.layout.frag, container, false);

    flipCamera = (ToggleButton) v.findViewById(R.id.flipper);

    // Create an instance of Camera
    mCamera = getCameraInstance();

    // Create our Preview view and set it as the content of our activity.
    mPreview = new CameraPreview(getContext(), mCamera);
    FrameLayout preview = (FrameLayout) v.findViewById(R.id.camera_preview);
    preview.addView(mPreview);

    flipCamera.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // TODO Auto-generated method stub
            try{
                mCamera.stopPreview();

                if(isChecked){
                    mCamera=openFrontFacingCamera();
                }
                else{
                    mCamera=openBackFacingCamera();
                }
                mCamera.startPreview();
            }catch(Exception exp){
                Log.i("#LOGTAG","EXCEPTION "+exp);
            }
        }
    });

    return v;
}

private Camera openBackFacingCamera() {
    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_BACK) {
            cam = Camera.open(camIdx);
        }
    }

    return cam;
}

private Camera openFrontFacingCamera() {
    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) {
            cam = Camera.open(camIdx);
        }
    }

    return cam;
}

/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
    Camera c = null;
    try {
        c = Camera.open(); // attempt to get a Camera instance
    }
    catch (Exception e){
        // Camera is not available (in use or does not exist)
    }
    return c; // returns null if camera is unavailable
}

}


The problem is that It always throws an Exception as:

I/#LOGTAG: EXCEPTION java.lang.RuntimeException: Fail to connect to camera service


if I use my code as:

              try{
                mCamera.stopPreview();
                mCamera.release();
                if(isChecked){
                    mCamera=openFrontFacingCamera();
                }
                else{
                    mCamera=openBackFacingCamera();
                }
                mCamera.startPreview();
            }catch(Exception exp){
                Log.i("#LOGTAG","EXCEPTION "+exp);
            }

My preview Freezes and comes back when i click the back button!


What I am doing Wrong? Is it the right way to switch between cameras? Can somebody help me please?

Thanks in advance!

Simply open the desired camera like this :

For front camera:

c = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);

For back camera:

c = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);

And make sure that you always release your camera when you are done or in the onPause method of your fragment using following code otherwise camera instance will never be released and even your main camera app will not be able to acquire it.

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

For anyone in the future facing the same problem. The error happens when the camera is already in use, I fixed the problem by first releasing the camera then setting it to null and opening it again.

//for front camera
 camera.release();
 camera = null;
 camera =  Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);

//for back camera
 camera.release();
 camera = null;
 camera =  Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM