Writing Code for Different API Levels
How do you handle changes in the Android Application Programming Interface (API) in code? By placing code that uses changed APIs into a separate class, then wrapping the use of that class in a test. The test is comparing the device’s API level against the code’s target API level. The Build class provides the relevant version numbers to use in the test. However, there are other considerations in supporting multiple API versions. These factors are explored in this article.
New versions of Android provide new classes, additions to existing classes and deprecated classes and methods. (Deprecated classes and methods are those that are no longer required and will be removed in future releases.) These changes are due to the Android platform continuously evolving to take advantage of new hardware, new ideas and to improve performance.
Reference Documentation API Level Filter
The Android Reference documentation has details on all the classes in all the APIs. Each part of a class has a label to denote in which API level it first appeared. The API documentation can apply a filter based on API level to grey out the classes and parts of classes that were not available prior to a give API version.
The Android API Differences Report
To see an overview of the changes between an Android API level and the previous API release view the Android API Differences Report. The report is viewed online at the Android Developers web site. The address is http://developer.android.com/sdk/api_diff/X/changes.html where X is the API level to examine the differences from the previous level. For example if X is 9 then the differences report show the changes from API level 8 (Froyo) to API level 9 (Gingerbread). A link to each differences report is in the post Android Versions Numbering and API Levels.
Reading the Android Devices API Version
The API version used by an Android device is read from the static Build class in the android.os package. The Build.VERSION.SDK_INT returns the API level. The various API levels are defined in Build.VERSION_CODES.
For example here is some code to test for API level 9 (the first Android Gingerbread release):
The App running this code must have the minSdkVersion attribute in the manifest (AndroidManifest.xml) set to 4 (Donut) or higher. Prior to API level 4 SDK_INT was not available, it was Build.VERSION.SDK, a string. There are very few devices around early than API level 4 so setting the minSdkVersion to 4 or later should not be an issue, however, a workaround is discussed later.
Detect Other Android API Levels
The above code is easily extended to detected other API levels. So to detect API level 8, Froyo, the code becomes: Continue reading