Here's a question for all Android programmers out there:
When using old and new API methods in my apps, I found two ways to approach the different API methods.
Test for SDK_INT as in
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { holder.content.setBackground(background); } else { holder.content.setBackgroundDrawable(background); }
Program a "Compat" class that uses reflection to test for method existence as in
private static final Method sApplyMethod = findApplyMethod(); private static Method findApplyMethod() { try { Class<?> cls = SharedPreferences.Editor.class; return cls.getMethod("apply"); } catch (NoSuchMethodException unused) { // fall through } return null; } public static void apply(final SharedPreferences.Editor editor) { if (sApplyMethod != null) { try { sApplyMethod.invoke(editor); return; } catch (InvocationTargetException unused) { // fall through } catch (IllegalAccessException unused) { // fall through } } editor.commit(); }
Now, the latter one is taking from a great book "50 Android hacks" by Carlos Sessa. I was taught that using exception handling for flow control is a bad thing and not to be done. If you can test against something, don't deliberately run into exception handling. Thus, method 2 would not be considered "clean".
But: on a mobile device, which is the preferred approach? Which one is faster on the long run?
Thanks for all your opinions!