I want to use the switch camera function. Currently I have Developed a Camera Object That working fine for back-camera but not working for front-camera. And I am unable to find a solution for switching between front and back cameras. Here is My Code..!
public class MyCamera extends Activity implements SurfaceHolder.Callback,
Camera.ShutterCallback, Camera.PictureCallback {
Camera mCamera;
SurfaceView mPreview;
String filePath;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_preview);
mPreview = (SurfaceView) findViewById(R.id.preview);
mPreview.getHolder().addCallback(this);
mPreview.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mCamera = Camera.open();
}
@Override
public void onPause() {
super.onPause();
mCamera.stopPreview();
}
@Override
public void onDestroy() {
super.onDestroy();
mCamera.release();
Log.d("CAMERA", "Destroy");
}
public void onCancelClick(View v) {
finish();
}
public void onSnapClick(View v) {
mCamera.takePicture(this, null, null, this);
}
@Override
public void onShutter() {
Toast.makeText(this, "Click!", Toast.LENGTH_SHORT).show();
}
@Override
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream fos = null;
try {
filePath = "/sdcard/test.jpg";
fos = new FileOutputStream(filePath);
fos.write(data);
fos.close();
// Log.d("Log", "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("Log", "onPictureTaken - wrote bytes: " + data.length);
} catch (IOException e) {
e.printStackTrace();
Log.d("Log", "onPictureTaken - wrote bytes: " + data.length);
} finally {
Intent i = getIntent();
i.putExtra("Path", filePath);
setResult(RESULT_OK, i);
finish();
}
camera.startPreview();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(Camera.CameraInfo.CAMERA_FACING_FRONT, info);
int rotation = this.getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break; // Natural orientation
case Surface.ROTATION_90:
degrees = 90;
break; // Landscape left
case Surface.ROTATION_180:
degrees = 180;
break;// Upside down
case Surface.ROTATION_270:
degrees = 270;
break;// Landscape right
}
int rotate = (info.orientation - degrees + 360) % 360;
Camera.Parameters params = mCamera.getParameters();
params.setRotation(rotate);
mCamera.setParameters(params);
mCamera.setDisplayOrientation(90);
mCamera.startPreview();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
mCamera.setPreviewDisplay(mPreview.getHolder());
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.i("PREVIEW", "surfaceDestroyed");
}
}
Try below code
mCamera= Camera.open(cameraId);
0 for CAMERA_FACING_BACK
1 for CAMERA_FACING_FRONT
Reference Camera.open(int)