I found some questions about this, but there are no answers, so I hope someone can have some understanding. When I try to swap the camera, I call the swapCamera function below. However, the camera preview simply freezes (the application did not freeze, although only viewing the camera in real time).
When I open the application for the first time, everything works fine. However, I noticed something interesting. When I exit the memory address of the _surfaceHolder object (i.e., my SurfaceHolder object), it gives me one value, but whenever I request this value after the application finishes running and that's it, this memory address has changed.
Also, the error he gives me when I swapCamera is very confused. I left _surfaceHolder before passing it to the camera in _camera.setPreviewDisplay(_surfaceHolder);
and it is not null before it passes.
Any help is greatly appreciated.
I noticed an interesting behavior
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback
{
private SurfaceHolder _surfaceHolder;
private Camera _camera;
boolean _isBackFacing;
public CameraPreview(Context context, Camera camera) {
super(context);
_camera = camera;
_isBackFacing = true;
_surfaceHolder = getHolder();
_surfaceHolder.addCallback(this);
}
void refreshCamera()
{
try {
_camera.setPreviewDisplay(_surfaceHolder);
_camera.startPreview();
} catch (IOException e) {
Log.d("iCamera", "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceCreated(SurfaceHolder holder)
{
refreshCamera();
}
public void surfaceDestroyed(SurfaceHolder holder)
{
_surfaceHolder.removeCallback(this);
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h)
{
if (_surfaceHolder.getSurface() == null){
return;
}
try {
_camera.stopPreview();
} catch (Exception e) {
}
_camera.setDisplayOrientation(90);
refreshCamera();
}
public void swapCamera()
{
Camera cam = null;
int cameraCount = Camera.getNumberOfCameras();
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
_camera.stopPreview();
_camera.release();
for (int i = 0; i < cameraCount; i++)
{
Camera.getCameraInfo(i,cameraInfo);
if(cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT && _isBackFacing == true)
{
try
{
_camera = Camera.open(i);
}catch (RuntimeException e)
{
Log.e("Error","Camera failed to open: " + e.getLocalizedMessage());
}
}
if(cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK && _isBackFacing == false)
{
try
{
_camera = Camera.open(i);
}catch (RuntimeException e)
{
Log.e("Error","Camera failed to open: " + e.getLocalizedMessage());
}
}
}
_isBackFacing = !_isBackFacing;
refreshCamera();
}
}
source
share