Search code examples
androidandroid-cameraandroid-api-levels

How to target multiple API levels?


I am looking to use Android's Camera.open() method on two separate API levels. First is API level 7, which is 2.1 and higher and the second is 2.3.3 & 2.3.4 which are API level 9.

On API level 7 and 8 the Camera.open method does not take any arguments. On API level 9 and above, the camera takes an integer argument that supplies it the cameraId to use.

How can I target both API levels in the same code? Something similar to this pseudo code:

Camera lCamera;
if (Platform.APILevel < 7){
  lCamera.open();
}else { 
  lCamera.open(0);
}

Solution

  • We often do reflection detection. Something like:

        public Camera getCamera() {
            try {
                Method method = Camera.class.getMethod("open", Integer.TYPE);
                return (Camera) method.invoke(null, 0);
            } catch (Exception e) {
                    // Yes, I really want to handle all exceptions here!!!!
                    Log.d(TAG,"Error when trying to invoke Camera.open(int), reverting to open()",e);
                    return Camera.open();
            }
        }