I'm working on an app that targets API 11 (3.0) but minSDKVersion is 7 (2.1).
I generate my PreferenceActivity programmatically instead of with XML. In Honeycomb, preference layouts have a built-in spot for an icon that can go next to each preference. You can set it with prefScreen.setIcon(R.drawable.my_icon);
So I don't want to do this on API 7-10. Is this sufficient protection from crashes?
if (android.os.Build.VERSION.SDK_INT>=11)
prefScreen.setIcon(R.drawable.myIcon);
The more elaborate solution that I know is safe is to use reflection to check if that method exists before trying to use it.
According to http://developer.android.com/training/basics/activity-lifecycle/starting.html, it's implied that it's safe to use the SDK_INT constant on Android 2.0 and above to wrap calls to newer APIs, without using reflection.
Caution: Using the SDK_INT to prevent older system's from executing new APIs works in this way on Android 2.0 (API level 5) and higher only. Older versions will encounter a runtime exception.
This worked for me:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB){
//code
}
If the method is not available on a lower versions of the platform, it will crash when the file is loaded by the system (it won't even make it to execution of your if
statement)
You should look at the article on Lazy Loading to do the reflection on the Android Dev Blog
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With