2

Why should I bother using reflection as discussed here, if I can simply test Android version from Build.VERSION.SDK_INT and conditionally run functions not available on lower API versions?

That article discussed how to get method ID, handle exceptions, etc, which seems more complicated than simply using:

if(Build.VERSION.SDK_INT>=11){
    // some Honeycomb code
    // example: findViewById(R.id.root).setSystemUiVisibility(View.STATUS_BAR_HIDDEN);
}

This code works fine for me on various devices (2.2 / 3.2 / etc).

Thanks

2
  • If you by "some Honeycomb code" mean "i create a new class that contains the honeycomb code and call a method/do something with that" your method should work - otherwise your app would just crash with an exception when you try to load the code on something that isn't Honeycomb (or later)
    – Jens
    Oct 7, 2011 at 6:42
  • I mean for example calling View.setSystemUiVisibility which is implemented since API 11. Oct 7, 2011 at 6:50

1 Answer 1

0

Your proposal won't work (without reflection) when running on an older Android system, if the code hidden in "// some Honeycomb code" uses Class or Method names that only exist in the Honeycomb API. The root of the problem is that all classes referenced from code are loaded when the class is loaded. You need to use reflection to delay resolution of the code containing Honeycomb references until run-time.

Specifically, if you have a class:

class MyUseOfFeatures {
   public void doSomething() {
       if (TestIfPhoneHasFancyHoneycombFeature()) {
          Object example = android.util.JsonReader(); // JsonReader is new in 3.0
       }
}

Then when the JVM (er, DVM?) loads the bytecode for this class it will try and resolve the android.util.JsonReader name when the class is loaded (presumably when your application is loaded).

If you only rely on some behavior of Honeycomb (not any any new classes, methods or fields), then you'd be fine to just test the build number.

6
  • As I wrote, above code works correctly on API 8 and API 13. So I don't see the problem you mention. Oct 7, 2011 at 6:48
  • I added example in the question. Oct 7, 2011 at 6:52
  • Huh, as I understand things, the View.setSystemUiVisibility reference should fail to be resolved when that code loads into any pre-3.0 Android system.
    – P.T.
    Oct 7, 2011 at 7:31
  • True, it may fail to resolve, but my code will never call it on API<11. That's original question - if I can filter such calls by checking API version. Oct 7, 2011 at 7:45
  • @mice It works in API level 8 but it doesn't work for API level 4 (Android 1.6). See stackoverflow.com/questions/6495007/…
    – Dan Dyer
    Oct 10, 2011 at 20:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.