Below is my barcode scanner activity, everything works fine except for the setAutoFocusEnabled(true). It returns a message on runtime that says my device does not support au
So after two days of struggle I finally managed to "concoct" a fix. But Android development team should seriously look into why setAutoFocusEnabled(true) doesn't work on devices with Auto Focus.
Here is my fix, hope it saves someone else some time:
@Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP) {
float x = event.getX();
float y = event.getY();
float touchMajor = event.getTouchMajor();
float touchMinor = event.getTouchMinor();
Rect touchRect = new Rect((int)(x - touchMajor / 2), (int)(y - touchMinor / 2), (int)(x + touchMajor / 2), (int)(y + touchMinor / 2));
this.submitFocusAreaRect(touchRect);
}
return super.onTouchEvent(event);
}
private void submitFocusAreaRect(final Rect touchRect) {
Field[] declaredFields = CameraSource.class.getDeclaredFields();
for (Field field : declaredFields) {
if (field.getType() == Camera.class) {
field.setAccessible(true);
try {
Camera camera = (Camera) field.get(cameraSource);
if (camera != null) {
Camera.Parameters cameraParameters = camera.getParameters();
if(cameraParameters.getMaxNumFocusAreas() == 0) {
return;
}
Rect focusArea = new Rect();
focusArea.set(touchRect.left * 2000 / cameraView.getWidth() - 1000,
touchRect.top * 2000 / cameraView.getHeight() - 1000,
touchRect.right * 2000 / cameraView.getWidth() - 1000,
touchRect.bottom * 2000 / cameraView.getHeight() - 1000);
ArrayList<Camera.Area> focusAreas = new ArrayList<>();
focusAreas.add(new Camera.Area(focusArea, 1000));
cameraParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
cameraParameters.setFocusAreas(focusAreas);
camera.setParameters(cameraParameters);
camera.autoFocus(this);
}
} catch (IllegalAccessException | RuntimeException e) {
e.getMessage();
}
break;
}
}
}
Now I can scan barcodes with the rear camera as well. Yay!