I have a method called switchCamera, I'm trying to switch camera from front to back on the click of a button, in one smooth transition. My application freezes when I call this method - I know I'm not doing something right. Can anyone help me out here?
Any help is much appreciated.
public void switchCamera(){
int camNum = 0;
camNum = Camera.getNumberOfCameras();
int camBackId = Camera.CameraInfo.CAMERA_FACING_BACK;
int camFrontId = Camera.CameraInfo.CAMERA_FACING_FRONT;
Camera.CameraInfo currentCamInfo = new Camera.CameraInfo();
//if camera is running
if (camera != null){
//and there is more than one camera
if (camNum > 1){
//stop current camera
camera.stopPreview();
camera.setPreviewCallback(null);
//camera.takePicture(null, null, PictureCallback);
camera.release();
camera = null;
//stop surfaceHolder?
if (currentCamInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT){
//switch camera to back camera
camera=Camera.open(camBackId);
}
else{
//switch camera to front camera
camera=Camera.open(camFrontId);
}
//switch camera back on
//specify surface?
try {
camera.setPreviewDisplay(surfaceHolder);
camera.setPreviewCallback((PreviewCallback) this);
camera.startPreview();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
First you need to destroy the SurfacePreview of previous camera, then need to create a new object of camera(Back/Front)
After a long search finally i can switched camera successfully. mjosh's answer is a useful answer but it did not worked for me. The trick i found finally is create new
CameraPreview
class and add it again.Here is my
CameraPreview
class.My
openCamera
method which i open camera with it:Before you create
CameraPreview
you have to calculate the rotation of camera and set it asdisplayOrientation
And i get
cameraId
like below:And finally my
SwtichCamera
button works like this:This is a working solution for me. I hope this'll help you some others too.
Edit: Camera preview can be a problem for Samsung devices. Here's an alternative method for getting best preview size.