Android API Level, backward and forward compatibility
Jun 9, 2019 · 8 min read
If you get to read this article it might mean you are wondering things like:
- What is an API?
- What does API Level mean?
- How to use compileSdkVersion, minSdkVersionor targetSdkVersion?
- How can I ensure my app will work properly on devices with different versions of the OS?
All these concepts are related to each other and I will try to clarify them to you in this article in a simple but effective way.
In order to do so, we need to have in mind the difference between SDK and API in software development and the meaning of API Level in the Android ecosystem.
In Android, it’s true that th e re is a 1:1 relationship between the SDK and the API and often these two terms are used as synonymous, but it’s important to understand they are not the same thing.
But it’s correct to say that for each Android version there is an SDK and there is an equivalent API and API Level.
It stands for Software Development Kit. Think of the word “kit”… it is exactly a collection or a set of different tools, libraries, documentation, samples to help developers to build, debug and run Android apps. Along with an SDK, an API is provided.
Opening the SDK Manager in Android Studio shows much clearer what is part of an Android SDK.
The first tab SDK Platform lists the SDKs of each Android version.
As per example, shown in the picture below, Android 9.0 (aka Pie) SDK contains:
- Android SDK Platform 28 (that’s the framework API)
- Source code for Android 28 (that’s the implementation of the API, as you can see is optional… keep this in mind)
- and a bunch of other stuff… like different system images for the Android emulator.
The second tab SDK Tools shows a bunch of other tools which are still part of the SDK, but platform version independent, which means they might be released or updated separately.
It stands for Application Programming Interface. It is simply an interface, an abstraction layer that allows communications between two different “pieces” of software. It works as a contract between the provider (e.g. a library) and the consumer (e.g. an app)
It is a set of formal definitions such as classes, methods, functions, modules, constants that can be used by other developers to write their code. Also, an API does not include implementation.
API Level
API Level is an integer value that uniquely identifies the framework API revision offered by a version of the Android platform.
Usually, updates to the framework API are designed so that the new API remains compatible with earlier versions of the API, for this reason, most of the changes to the new API are additive and the old parts of API are deprecated but not removed.
But now someone could argue…
if an Android API doesn’t provide implementation and the SDK Manager offers an optional downloadable API source code as part of the SDK, where is the actual implementation?
The answer is easy. On the device.
Let’s go through this quickly…
From source code to an APK file
Generally, an Android project is composed by the code developers write using Android API (the application module), plus some other libraries/dependencies (.jar, AAR, local modules…etc) and some resources.
The compilation process converts Java/Kotlin code, dependencies included (one reason to shrink your code!), into DEX byte-code and then compressed everything into an APK file along with some resources. At this stage, the implementation of the API is not included in the resulting APK!
DEX files and Android Runtime
The Android Runtime is where all the dirty job is done and where DEX files are executed. It is made of two main components:
- a Virtual Machine in order to take advantages of code portability and platform independence. Starting from Android 5.0 (Lollipop) the old runtime environment, Dalvik Virtual Machine, has been totally replaced by the new Android RunTime (ART). Dalvik used a JIT compiler, whereas ART uses AOT (Ahead of time) compilation plus JIT for runtime code profiling.
- Core Libraries are standard Java libraries and Android libraries. In simple words, this is where the implementation of the API resides.
The API version available at this level is the one offered by the version of the Android platform in which the app is running.
For example, if the actual device has installed Android 9 (Pie), all the APIs until API Level 28 are available.
If the few key concepts of how the Android Runtime works and what is the role of the API is clear so far, then it should be quite easy to understand backward/forward compatibility and the usage of compileSdkVersion, minSdkVersion and targetSdkVersion.
compileSdkVersion
This value is used only to tell Gradle what version of the SDK to compile your app with. For developers, it allows accessing to all the APIs available up to API Level set to compileSdkVersion.
It is strongly recommended to compile against the latest SDK version:
- a high API Level allows developers to take advantages of the latest APIs and capabilities provided by new platforms.
- in order to use the latest SupportLibrary, compileSdkVersion has to match the SupportLibrary version too.
For example, in order to use SupportLibrary-28.x.x, compileSdkVersion has to be set to 28 as well. - for migrating to/using AndroidX, compileSdkVersion has to be set at 28 at least.
- getting ready to satisfy Google Play’s target API level requirement. As announced by Google, in order to spread new Android versions quicker out in the market, every year Google will enforce a minimum target API Level for new applications and updates. More info here and here.
Android applications are forward-compatible with new versions of the Android platform because API changes are generally additive and old APIs might be deprecated, but not removed.
That means forward compatibility is basically guaranteed by the platform and running an application on a device with a higher API Level than the one specified in compileSdkVersion does not have any runtime issue, the application runs as expected on newer platform versions too.
App + compileSdkVersion = 26 and using an API xyz() introduced in API Level 26 can run on a device with Android 8 Oreo (API Level 26).
The same app can run on a device with Android 9 Pie (API Level 28) since the API xyz() is still available in API Level 28 .
minSdkVersion
This value specifies the minimum API Level in which the application is able to run. It’s the minimum requirement. If not specified, the default value is 1.
It is developers responsibility to set a proper value and ensure the application runs properly down to this API Level. This is called backward compatibility.
During development, Lint will also warn developers when trying to use any API above the specified minSdkVersion. It is really important to not ignore these warnings and fix them!
In order to provide backward compatibility, developers can check at runtime the platform version and use a new API on newer versions of the platform and old API on older versions or, depending on the case, using some static libraries which offer backward compatibility.
It is also important to mention Google Play Store uses this value to determinate if an app can be installed on a specific device by matching the device platform version with the app minSdkVersion.
Developers should be really careful when picking this value since backward compatibility is not guaranteed by the platform.
Picking a “right” value for a project is also a business decision since it affects how big is the audience the application is made for. Have a look at the platform distribution.
For example:
App + compileSdkVersion = 26 + minSdkVersion = 22 and using an API xyz() introduced in API Level 26 can run on a device with Android 8 Oreo (API Level 26).
The same app can be installed and run on an older device with Android 5.1 Lollipop (API Level 22), where the API xyz() does not exist. If no backward compatibility has been provided by developers either with runtime checks or some sort of libraries, then the application will crash as soon as it tries to access the API xyz().
targetSdkVersion
This value specifies the API Level on which the application is designed to run.
It doesn’t have to be confused with compileSdkVersion. The latter is only used at compile time and it makes new APIs available to developers. The former, instead, is part of the APK (as well as the minSdkVersion) and changes runtime behavior. It is the way developers can control forward compatibility.
Sometimes there might be some API changes on the underlying system that can affect how an application behaves when is running on a new runtime environment.
Targeting an application to a specific version enables all of those system runtime behaviors, which are dependent on that specific version of the platform. If an app is not ready to support these runtime behavior changes it is likely going to crash.
A simple example is the Runtime Permission, which has been introduced with Android 6 Marshmallow (API Level 23).
It is possible for an application to compile against API Level 23, but targeting API Level 22 if it is not ready yet to adopt the new runtime permission model.
In this way, an application can still be forward compatible without enabling the new runtime behavior.
Anyway, as already mentioned Google is enforcing apps to satisfy new target API level requirements, so it should be a high priority to always update this value.
Putting all together at the end there is a clear relationship
Keep in mind it is highly recommended to compile against the latest API Level and try to have targetSdkVersion == compileSdkVersion.
Источник
Изменение уровня API Android Studio
Я хочу изменить минимальную версию SDK в Android Studio от API 12 до API 14. Я попытался изменить ее в файле манифеста, т.е.
и перестроить проект, но я до сих пор получаю IDE от Android Studio, вызывая некоторые ошибки. Я предполагаю, что мне нужно установить минимальный SDK в «свойствах проекта» или что-то подобное, поэтому среда IDE распознает изменение, но я не могу найти, где это делается в Android Studio.
13 ответов
Если вы хотите обновить minSdkVersion в существующем проекте.
- Обновить build.gradle(Module: app) . Убедитесь, что он находится под Gradle Script, и он НЕ build.gradle(Project: yourproject) .
- Кнопка синхронизации gradle (обновлены все проекты gradle)
- Реконструкция проекта
После обновления build.gradle minSdkVersion вам нужно щелкнуть по кнопке, чтобы синхронизировать файл gradle ( «Синхронизировать проект с gradle файлами» ). Это очистит маркер.
Обновление manifest.xml, например. удаление каких-либо ссылок на уровни SDK в файле манифеста больше не требуется в Android Studio.
Для пользователей студии Android:
- щелкните правой кнопкой мыши каталог приложения
- выберите параметр «настройка модуля»
- измените платформу ADK как то, что вам нужно
- Нажмите «Применить»
gradle автоматически перестроит проект.
Как сейчас Android Studio стабильна, есть простой способ сделать это.
- Щелкните правой кнопкой мыши файл проекта
- Выберите «Открыть настройки модуля»
- Перейдите на вкладку «Ароматизаторы».
- Выберите Min SDK Version из выпадающего списка
PS: Хотя на этот вопрос уже был дан ответ, но Android Studio немного изменила его стабильный выпуск. Таким образом, простой прямой способ поможет любому новому поиску ответа приземлиться здесь.
В студии Android вы можете легко нажать:
- Ctrl + Shift + Alt + S .
- Если у вас есть более новая версия android studio , чем сначала нажмите на приложение. чем продолжить с шага 3 следующим образом.
- Откроется окно с набором параметров
- Перейдите в Flavors, и на самом деле все, что вам нужно
Вы также можете изменить versionCode вашего приложения.
В build.gradle измените minSdkVersion 13 на minSdkVersion 8 . Это все, что вам нужно сделать. Я решил свою проблему, только делая это.
В соответствии с этим ответом вы просто не включаете minsdkversion в файл manifest.xml, а система сборки будет использовать значения из файла build.gradle и поместите информацию в окончательный apk.
Поскольку система сборки нуждается в этой информации, это имеет смысл. Вам не нужно указывать эти значения два раза.
Вам просто нужно синхронизировать проект после изменения файла build.gradle , но Android Studio 0.5.2 отображает желтую строку состояния поверх окна редактора build.gradle, чтобы помочь вам
Также обратите внимание на наличие как минимум двух файлов build.gradle : один мастер и один для приложения/модуля. Тот, который нужно изменить, находится в приложении/модуле, он уже включает свойство minSdkVersion во вновь сгенерированном проекте.
Если у вас возникли проблемы с указанием целевой SDK для API Google вместо базового пакета SDK, просто измените compileSdkVersion 19 на compileSdkVersion «Google Inc.:Google APIs:19»
Также, как и обновление манифеста, обновите файл модуля build.gradle тоже (он указан в панели проекта чуть ниже манифеста — если там нет minSdkVersion ), вы смотрите на неправильный, так как там пара). Перестроить и все должно быть хорошо.
Для последней версии Android Studio v2.3.3 (11 октября 2017 года):
1. Нажмите View в строке меню
2. Нажмите «Открыть настройки модуля» 3. Откройте вкладку Flavors
4. Выберите Min Sdk версию, которая вам нужна
6. Нажмите OK
Источник