Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Build.VERSION_CODES possibly work?

Tags:

java

android

I'm confused on the internal workings of the Android API's.

If my app is compiled against Android 5.0, then it's acceptable that the following works on a device running Android 5.0 and up:

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)

However, this still works if I run it on a device running older versions of Android. My assumption is that the library on that device doesn't have a definition for the variable Build.VERSION_CODES.LOLLIPOP. Then how can the variable be resolved on those older devices when the app runs this code?

like image 699
AxiomaticNexus Avatar asked Nov 15 '14 01:11

AxiomaticNexus


1 Answers

Then how can the variable be resolved on those older devices when the app runs this code?

Simple: there is no variable.

Build.VERSION_CODES.LOLLIPOP is a static final int. The javac-generated bytecodes will inline the int value when you reference Build.VERSION_CODES.LOLLIPOP, rather than doing the lookup for that value at runtime. Since the bytecodes contain the int, your APK contains the int, and therefore you are not dependent upon the device's edition of the framework to supply the int to you.

Build.VERSION.SDK_INT is not a static final int, and therefore that value is looked up at runtime.

like image 131
CommonsWare Avatar answered Sep 27 '22 21:09

CommonsWare