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 i开发者_如何学JAVAn the same code? Something similar to this pseudo code:
Camera lCamera;
if (Platform.APILevel < 7){
lCamera.open();
}else {
lCamera.open(0);
}
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();
}
}
Generally speaking, you just target the lowest API level you can get away with. Anything built for API level 7 will work for API level 8, 9, 10, etc. In this case, just call lCamera.open();
and it will choose the first back-facing camera found. If you want to use a front camera, you have to use the higher level API level 9.
You can get the API level by reading the final static
integer android.os.Build.VERSION.SDK_INT
.
In your manifest, make sure that you set android:minSdkVersion
AND android:targetSdkVersion
.
精彩评论