I want to check if the method Camera.Parameters.getHorizontalViewAngle()
exists on the device (it's only available from API 8 and my min SDK API is 7). I tried to use "reflection", as explained here, but it catches an error saying the number of arguments is wrong:
java.lang.IllegalArgumentException: wrong number of arguments
Anybody could help?
Camera camera;
camera = Camera.open();
Parameters params = camera.getParameters();
Method m = Camera.Parameters.class.getMethod("getHorizontalViewAngle", new Class[] {} );
float 开发者_高级运维hVA = 0;
try {
m.invoke(params, hVA);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
m.invoke(params, hVA);
should be
m.invoke(params, null);
Camera.Parameters.getHorizontalViewAngle()
doesn't take any arguments and the above line has the argument hVA. If you're looking for the return variable do hVA = m.invoke(params, null);
Personally, I recommend conditional class loading, where you isolate the new-API code in a class that you only touch on a compatible device. I only use reflection for really lightweight stuff (e.g., finding the right CONTENT_URI
value to use for Contacts
or ContactsContract
).
For example, this sample project uses two implementations of an abstract class to handle finding a Camera object -- on a Gingerbread device, it tries to use a front-facing camera.
Or, this sample project shows using the action bar on Honeycomb, including putting a custom View in it, while still maintaining backwards compatibility to older versions of Android.
I know this is a hack, but why can't you put the first call to the method in a try/catch of it's own, and nest the rest of your try/catch code in there. If the outer catch executes, the method doesn't exist.
精彩评论