开发者

Using Java reflection vs checking Build.VERSION.SDK_INT

开发者 https://www.devze.com 2023-04-11 03:37 出处:网络
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?

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).setSystemU开发者_运维问答iVisibility(View.STATUS_BAR_HIDDEN);
}

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

Thanks


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号