Android version check

2019-02-02 20:07发布

问题:

I'm not new to Android and I'm well used to the version handling and how to condition it, but when I see this it troubles me...

// Check if we're running on Android 5.0 or higher
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    // Call some material design APIs here
} else {
    // Implement this feature without material design
}

On any device pre lollipop this line would crash the app because the Build.VERSION_CODES.LOLLIPOP field does not exists... so why is this in the recommended solution in the documentation?

I'm really wondering what am I missing?

回答1:

Well, you must compile your project with the latest SDK version. Your constants are replaced with corresponding integer values during compilation. No matter what version of Android you run the application on - integers are the same



回答2:

Well in that case use this

// Check if we're running on Android 5.0 or higher
if (Build.VERSION.SDK_INT >= 21) {
    // Call some material design APIs here
} else {
    // Implement this feature without material design
}

Build.VERSION_CODES.LOLLIPOP = 21



回答3:

Try this one

 if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
       // Marshmallow+
   }else{
        //below Marshmallow
}

Note: Build.VERSION_CODES.LOLLIPOP_MR1==22

    Build.VERSION_CODES.M==23