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

Pointer Null
  • 39,597
  • 13
  • 90
  • 111
  • 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 07 '11 at 06:42
  • I mean for example calling View.setSystemUiVisibility which is implemented since API 11. – Pointer Null Oct 07 '11 at 06:50

1 Answers1

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.

P.T.
  • 24,557
  • 7
  • 64
  • 95
  • As I wrote, above code works correctly on API 8 and API 13. So I don't see the problem you mention. – Pointer Null Oct 07 '11 at 06:48
  • I added example in the question. – Pointer Null Oct 07 '11 at 06: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 07 '11 at 07: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. – Pointer Null Oct 07 '11 at 07:45
  • @mice It works in API level 8 but it doesn't work for API level 4 (Android 1.6). See http://stackoverflow.com/questions/6495007/verifyerror-deploying-on-api-1-6 – Dan Dyer Oct 10 '11 at 20:27
  • Thanks Dan. Assuming that if I target Android 2.1+, this will work. – Pointer Null Oct 11 '11 at 04:58