- Android platform api level
- Android NDK Native APIs
- On this page
- Overview
- Major Native API Updates
- Android API level 3
- C library
- C++ library
- Android-specific log support
- ZLib compression library
- Dynamic linker library
- Android API level 4
- OpenGL ES 1.x Library
- Android API level 5
- OpenGL ES 2.0 library:
- Android API level 8
- jnigraphics
- Android API level 9
- OpenSL ES
- Android native application APIs
- Android API level 14
- OpenMAX AL
- OpenSL ES
- Android API level 18
- OpenGL ES 3.0
- Android API level 21
- OpenGL ES 3.1
Android platform api level
API Level это просто целое число, которое однозначно идентифицирует ревизию рабочего окружения программных библиотек (framework API revision), которая предоставляется версией платформы (операционной системой) Android.
Платформа Android предоставляет framework API, которое могут использовать приложения для взаимодействия с нижележащей системой Android. Framework API состоит из:
• Базового набора пакетов и классов.
• Набора элементов XML и атрибутов для декларирования в файле манифеста (manifest file).
• Набора элементов XML и атрибутов для декларирования и доступа к ресурсам.
• Набора намерений (Intents).
• Набора разрешений доступа к ресурсам устройства и системы, которые приложение может запросить, а также защита ограничения доступа, встроенная в систему.
Каждая последующая версия платформы Android может включать в себя обновления предоставляемого framework API приложения Android.
Обновления framework API разработаны так, чтобы новый API оставался совместимым со всеми более старыми версиями API. Т. е. большинство изменений в API добавочные, и представляют новый функционал, или функционал, заменяющий старый. Поскольку части API были обновлены, то старые заменяемые части объявляются устаревшими и нежелательными для использования (deprecated), но эти старые части все же не удаляются, чтобы существующие приложения могли продолжать их использовать. В очень редких случаях части API могут быть модифицированы или удалены, но только в том случае, если это необходимо для обеспечения устойчивости API и безопасности приложения или системы. Все другие части API от старых ревизий переносятся в новые ревизии платформы без модификации.
Framework API, который поставляет платформа Android, указывается в виде целого числа, и этот идентификатор в виде целого числа называется «API Level». Каждая версия платформы Android поддерживает точно один API Level, несмотря на неявную поддержку всех более старых версий API Level (вплоть до API Level 1). Первоначальный релиз платформы Android предоставлял API Level 1 и с каждым новым релизом номер API Level последовательно увеличивался на единицу.
В таблице ниже указаны поддерживаемые API Level для каждой платформы Android. Для информации по относительным количествам устройств, которые работают на каждой версии, см. страничку [2].
Версия платформы | API Level | VERSION_CODE |
Android 4.4 | 19 | KITKAT |
Android 4.3 | 18 | JELLY_BEAN_MR2 |
Android 4.2, 4.2.2 | 17 | JELLY_BEAN_MR1 |
Android 4.1, 4.1.1 | 16 | JELLY_BEAN |
Android 4.0.3, 4.0.4 | 15 | ICE_CREAM_SANDWICH_MR1 |
Android 4.0, 4.0.1, 4.0.2 | 14 | ICE_CREAM_SANDWICH |
Android 3.2 | 13 | HONEYCOMB_MR2 |
Android 3.1.x | 12 | HONEYCOMB_MR1 |
Android 3.0.x | 11 | HONEYCOMB |
Android 2.3.3, 2.3.4 | 10 | GINGERBREAD_MR1 |
Android 2.3, 2.3.1, 2.3.2 | 9 | GINGERBREAD |
Android 2.2.x | 8 | FROYO |
Android 2.1.x | 7 | ECLAIR_MR1 |
Android 2.0.1 | 6 | ECLAIR_0_1 |
Android 2.0 | 5 | ECLAIR |
Android 1.6 | 4 | DONUT |
Android 1.5 | 3 | CUPCAKE |
Android 1.1 | 2 | BASE_1_1 |
Android 1.0 | 1 | BASE |
[Как используется API Level в Android]
Идентификатор API Level играет ключевую роль в предоставлении информации пользователям и разработчикам.
• API Level позволяет платформе (операционной системе) Android описать максимальную ревизию framework API, которую платформа поддерживает.
• API Level позволяет приложениям описать требуемую для них ревизию framework API.
• API Level позволяет системе обрабатывать инсталляции приложений на устройстве пользователя и определять, какие их них являются несовместимыми с текущей версией системы.
Подробнее про использовании API Level в приложении и системе Android см. [3].
[Совместимость приложений с новыми версиями операционной системы Android]
Application forward compatibility — под этим имеют в виду, что приложения Android обычно имеют «совместимость вперед». Т. е. старые приложения, которые скомпилированы в расчете на старую версию операционной системы, будут продолжать нормально работать на всех более новых операционных системах Android.
Поскольку большинство изменений framework API в операционной системе являются добавочными, то приложения Android, разработанные с указанной версией API (как указано по API Level) будут совместимы в будущем (forward-compatible) с последующими версиями платформ Android и более высокими уровнями API level. Приложения должны иметь возможность работать на всех последующих версиях платформы Android, за исключением изолированных случаев, когда приложение использует часть API, которая по некоторым причинам было удалена в поздней ревизии API.
Forward-совместимость важна, потому что множество устройств, работающих на Android, получают обновления системы на лету, по каналу Wi-Fi (over-the-air, OTA). Пользователь может установить Ваше приложение и успешно его использовать, и позднее получить OTA-обновление на новую версию платформы Android. Как только обновление установлено, Ваше приложение будет работать уже в новой версии рабочего окружения, на новом API (run-time version environment), и от этого нового API и возможностей системы будет зависеть работа Вашего приложения.
В некоторых случаях изменения в API могут влиять на Ваше приложение, когда оно работает в новом окружении. По этой причине Вам как разработчику важно понимать, как будет выглядеть приложение и как оно будет себя вести в новом системном окружении. Чтобы помочь Вам протестировать приложение в различных версиях платформ Android, пакет Android SDK, который Вы можете загрузить, включает многие платформы и версии API. Каждая платформа включает совместимый образ системы, который Вы можете запустить в AVD, для тестирования Вашего приложения.
Application backward compatibility — означает совместимость приложения со старыми версиями операционной системы Android. Приложения не обязательно будут обратно совместимы с версиями платформ Android, которые имеют более старую версию, чем версия системы, под которую приложение было скомпилировано.
Каждая новая версия платформы Android может включать новый framework API, который дает приложениям доступ к возможностям новой платформы, или заменяет существующие части API. Новый API доступен приложениями, когда они работают на новой платформе и, как уже упоминалось, также будет доступен и в более новых версиях платформы, как указано по API Level. С другой стороны, потому что более ранние версии платформы не включают в себя новый API, приложения, использующие новый API, не смогут работать на более старых платформах.
[Выбор версии платформы и API Level]
Когда Вы разрабатываете приложение под Android, то Вам нужно выбрать версию платформы, под которую будете компилировать приложение. Обычно желательно, чтобы приложение было скомпилировано под как можно малый номер API Level, которую Ваше приложение может поддерживать. Понятно почему — этим потенциально расширяется круг устройств, на которых Ваша программа сможет работать.
Вы можете задать минимально возможную версию платформы, компилируя приложения на низкую целевую версию платформы. После того, как определите самую низкую версию, Вам нужно создать AVD с соответствующей версией платформы (и API Level) и полностью протестировать Ваше приложение на этой платформе. Убедитесь, что установлен декларированный атрибут android:minSdkVersion в файле манифеста приложения, и его установленное значение соответствует API Level версии платформы.
[Декларирование минимальной версии API Level]
Если Вы компилируете приложение, которое использует API или системные возможности, представленные в последней версии платформы, Вы должны установить атрибут android:minSdkVersion в значение API Level этой последней версии платформы. Это обеспечит, что приложение будет установлено только на тех устройствах, которые будут совместимы с нужной версией платформы Android. В свою очередь это гарантирует, что Ваше приложение может функционировать должным образом на их устройствах.
Если Ваше приложение использует API, представленные в последней версии платформы, но не будет декларировать атрибут android:minSdkVersion, то оно будет правильно работать на устройствах, где работает последняя версия платформы, но не на устройствах, где работают более ранние версии платформы. В последнем случае приложения будут завершаться по ошибке во время выполнения, когда попытается использовать API, которое не существует в предыдущих версиях.
[Тестирование на верхних уровнях API Level]
После того, как скомпилировали приложение, Вы должны убедиться, что протестировали его на платформе, указанной в атрибуте android:minSdkVersion приложения. Чтобы сделать это, создайте AVD, которая использует версию платформы, требуемую приложением. Дополнительно, чтобы убедиться в forward-совместимости, Вы должны запустить и протестировать приложение на всех платформах, которые используют более высокий уровень API Level, чем использует Ваше приложение.
Android SDK включает в себя множество версий платформ, которые Вы можете использовать, включая последнюю версию, и предоставляет инструмент обновления (updater tool), который можно использовать для загрузки других необходимых версий платформ. Чтобы запустить updater, используйте инструмент командную строки android (на Windows это android.bat), находящийся в директории / tools directory. Вы можете запустить SDK updater, если выполните команду android sdk. Вы также можете сделать двойной клик на файле android.bat (под Windows) или android (под OS X/Linux). В ADT Вы можете также получить доступ к updater путем выбора меню Window -> Android SDK Manager.
Чтобы запустить приложение на другой версии платформы в эмуляторе, создайте отдельное виртуальное устройство AVD для каждой версии платформы, которую Вы хотели бы протестировать. Подробнее про AVD см. [5]. Если для тестирования Вы используете физическое устройство, убедитесь, что знаете API Level платформы, на которой запускаете приложение.
[Использование Provisional API Level]
В некоторых случаях может быть доступен «Ранний просмотр (Early Look)» платформы Android SDK. Это означает разработку для платформы, которая пока официально не появилась на рынке. Чтобы начать разработку на платформе, API которой еще не получила финальную версию, то не указывается API Level платформы. Вместо этого Вы должны использовать предварительный (provisional) API Level в манифесте приложения, когда делаете сборку приложения на указанной платформе. Provisional API Level не является числом, это строка, соответствующая кодовому имени еще не выпущенной версии платформы. Provisional API Level будет указан в примечаниях к релизу для ранних релизов SDK (Early Look SDK release), и эта строка чувствительна к регистру символов.
Использование provisional API Level разработано для того, чтобы защитить разработчиков и пользователей устройств от нежелательной публикации или инсталляции приложений, основанных на Early Look framework API, потому что на финальном образе системы приложение может работать не так, как ожидалось.
Provisional API Level будет допустим только при использовании Early Look SDK, и его можно использовать для запуска приложений только в эмуляторе. Приложения, использующие provisional API Level, никогда не могут быть установлены на устройство Android. После финального релиза платформы Вы должны заменить любые экземпляры provisional API Level в Вашем файле манифеста приложения на действительный идентификатор API Level в виде целого числа.
[Фильтрация документации на основе API Level]
Страницы документации на сайте разработчиков Android предоставляют фильтр «Filter by API Level» в правом верхнем углу на каждой страничке. Вы можете использовать этот контрол для того, чтобы просмотреть документацию только для частей API, которые действительно доступны для Вашего приложения, основываясь на API Level, который указан в android:minSdkVersion файла манифеста.
Чтобы использовать фильтрацию, поставьте галочку в чекбоксе для разрешения фильтрации, сразу ниже бокса поиска на странице. Затем установите контрол «Filter by API Level» в тот же API Level, который используется в Вашем приложении. Обратите внимание, что API, представленный в последующих версиях API Level нарисованы серым, и это содержимое будет замаскировано, потому что не будет доступно в Вашем приложении.
Фильтрация по API Level в документации не предоставляет просмотр, что нового представлено в каждом API Level. Фильтрация просто предоставляет метод для просмотра всего API, связанного с указанным API Level, когда исключаются элементы API, представленные в последующих API Levels.
Если Вы решили, что не хотите фильтровать документацию API, то просто отключите опцию, используя флажок. По умолчанию запрещена фильтрация по API Level, так что Вы можете увидеть полный full framework API, не обращая внимания на API Level.
Также имейте в виду, что документация по отдельным элементам API указывает API Level для каждого представленного элемента. API Level для пакетов и классов указывается как «Since » в правом верхнем углу содержимого каждой страницы документации. API Level для членов класса указан в соответствующем заголовочном файле.
Источник
Android NDK Native APIs
On this page
The Android NDK provides a set of native headers and shared library files that has gradually increased with successive releases of new Android API levels. This page explains these headers and files, and maps them to specific Android API levels.
Overview
There are two basic steps to enable your app to use the libraries that the NDK provides:
- Include in your code the headers associated with the libraries you wish to use.
- Tell the build system that your native module needs to link against the libraries at load time. For example, to link against /system/lib/libfoo.so , add the following line to your Android.mk file:
To list multiple libraries, use a space as a delimiter. For more information about using the LOCAL_LDLIBS variable, see Android.mk.
For all API levels, the build system automatically links the standard C libraries, the standard C++ libraries, real-time extensions, and pthread ; you do not need to include them when defining your LOCAL_LDLIBS variable. For more information about the C and C++ libraries, see Android API level 3.
Table 1 shows the correspondence between NDK-supported API levels and Android releases.
Table 1. NDK-supported API levels and corresponding Android releases.
NDK-supported API level | Android release |
---|---|
3 | 1.5 |
4 | 1.6 |
5 | 2.0 |
8 | 2.2 |
9 | 2.3 through 3.0.x |
12 | 3.1.x |
13 | 3.2 |
14 | 4.0 through 4.0.2 |
15 | 4.0.3 and 4.0.4 |
16 | 4.1 and 4.1.1 |
17 | 4.2 and 4.2.2 |
18 | 4.3 |
19 | 4.4 |
21 | 4.4W and 5.0 |
Each new release of NDK headers and libraries for a given Android API level is cumulative; you are nearly always safe if you use the most recently released headers when building your app. For example, you can use the NDK headers for Android API level 21 for an app targeting API level 16. By doing so, however, you increase your APK’s footprint.
For more information about Android API levels, see What is API Level?.
Major Native API Updates
Android API level 3
The NDK provides the following APIs for developing native code that runs on Android 1.5 system images and above.
C library
The C library headers for Android 1.5 are available through their standard names, such as stdlib.h and stdio.h . If a header is missing at build time, it’s because the header is not available on the 1.5 system image.
C++ library
An extremely minimal C++ support API is available. For more information on C++ library support, see C++ Library Support.
Android-specific log support
You can write your own wrapper macros to access this functionality. If you wish to perform logging, your native module should link to /system/lib/liblog.so . Implement this linking by including the following line in your Android.mk file:
ZLib compression library
You can use the Zlib compression library by including zlib.h and zconf.h . You must also link your native module against /system/lib/libz.so by including the following line in your Android.mk file:
Dynamic linker library
You can access the Android dynamic linker’s dlopen() , dlsym() , and dlclose() functions by including dlfcn.h . You must also link against /system/lib/libdl.so by including the following line in your Android.mk file:
Android API level 4
The NDK provides the following APIs for developing native code that runs on Android 1.6 system images and above.
OpenGL ES 1.x Library
The standard OpenGL ES headers gl.h and glext.h contain the declarations necessary for performing OpenGL ES 1.x rendering calls from native code.
To use these headers, link your native module to /system/lib/libGLESv1_CM.so by including the following line in your Android.mk file:
All Android-based devices support OpenGL ES 1.0, because Android provides an Open GL 1.0-capable software renderer that can be used on devices without GPUs.
Only Android devices that have the necessary GPU fully support OpenGL ES 1.1. An app can query the OpenGL ES version string and extension string to determine whether the current device supports the features it needs. For information on how to perform this query, see the description of glGetString() in the OpenGL specification.
Additionally, you must put a tag in your manifest file to indicate the version of OpenGL ES that your application requires.
The EGL APIs are only available starting from API level 9. You can, however, use the VM to perform some of the operations that you would get from those APIS. These operations include surface creation and flipping. For an example of how to use GLSurfaceView , see Introducing GLSurfaceView.
The san-angeles sample application provides an example of how to perform these operations, rendering each frame in native code. This sample is a small Android port of the excellent San Angeles Observation demo program.
Android API level 5
The NDK provides the following APIs for developing native code that runs on Android 2.0 system images and above.
OpenGL ES 2.0 library:
The standard OpenGL ES 2.0 headers and contain the declarations needed for performing OpenGL ES 2.0 rendering calls from native code. These rendering calls provide the ability to use the GLSL language to define and use vertex and fragment shaders.
To use OpenGL ES 2.0, link your native module to /system/lib/libGLESv2.so by including the following line in your Android.mk file:
Not all devices support OpenGL ES 2.0. An app can query the OpenGL ES version string and extension string to determine whether the current device supports the features it needs. For information on how to perform this query, see the description of glGetString() in the OpenGL specification.
Additionally, you must put a tag in your manifest file to indicate which version of OpenGL ES your application requires. For more information about the OpenGL ES settings for , see OpenGL ES.
The hello-gl2 sample application provies a basic example of how to use OpenGL ES 2.0 with the NDK.
The EGL APIs are only available starting from API level 9. You can, however, use the VM to perform some of the operations that you would get from those APIs. These operations include surface creation and flipping. For an example of how to use GLSurfaceView , see Introducing GLSurfaceView.
Note: The Android emulator does not support OpenGL ES 2.0 hardware emulation. Running and testing code that uses this API requires a real device with hardware that can support OpenGL ES 2.0.
Android API level 8
The NDK provides the following APIs for developing native code that runs on Android 2.2 system images and above.
jnigraphics
The jnigraphics library exposes a C-based interface that allows native code to reliably access the pixel buffers of Java bitmap objects. The workflow for using jnigraphics is as follows:
- Use AndroidBitmap_getInfo() to retrieve information from JNI, such as width and height, about a given bitmap handle.
- Use AndroidBitmap_lockPixels() to lock the pixel buffer and retrieve a pointer to it. Doing so ensures that the pixels do not move until the app calls AndroidBitmap_unlockPixels() .
- In native code, modify the pixel buffer as appropriate for its pixel format, width, and other characteristics.
- Call AndroidBitmap_unlockPixels() to unlock the buffer.
To use jnigraphics , include the header in your source code, and link against jnigraphics by including the following line in your Android.mk file:
Additional details about this feature are in the comments of the bitmap.h file.
Android API level 9
The NDK provides the following APIs for developing native code that runs on Android 2.3 system images and above.
EGL provides a native platform interface for allocating and managing OpenGLES surfaces. For more information about its features, see EGL Native Platform Interface.
EGL allows you to perform the following operations from native code:
- List supported EGL configurations.
- Allocate and release OpenGLES surfaces.
- Swap or flip surfaces.
The following headers provide EGL functionality:
- EGL/egl.h : the main EGL API definitions.
- EGL/eglext.h : EGL extension-related definitions.
To link against the system’s EGL library, add the following line to your Android.mk file:
OpenSL ES
Android native audio handling is based on the Khronos Group OpenSL ES 1.0.1 API.
The standard OpenSL ES headers OpenSLES.h and OpenSLES_Platform.h contain the declarations necessary for performing audio input and output from the native side of Android. The NDK distribution of the OpenSL ES also provides Android-specific extensions. For information about these extensions, see the comments in OpenSLES_Android.h and OpenSLES_AndroidConfiguration.h .
The system library libOpenSLES.so implements the public native audio functions. Link against it by adding the following line to your Android.mk file:
For more information about the OpenSL ES API, refer to $NDK/docs/Additional_library_docs/opensles/index.html , where $NDK is your NDK installation root directory.
Android native application APIs
Starting from API level 9, you can write an entire Android app with native code, without using any Java.
Note: Writing your app in native code is not, in itself, enough for your app to run in the VM. Moreover, your app must still access most features of the Android platform via JNI.
This release provides the following native headers:
For more information about these headers, see the NDK API Reference documentation, as well as the comments in the headers, themselves. Also, for more information about the larger topic of writing native apps, see Native Activities and Applications.
When you include one or more of these headers, you must also link against the libandroid.so library. To link against libandroid.so , include the following line in your Android.mk file:
Android API level 14
The NDK provides the following APIs for developing native code that runs on Android 4.0 system images and above.
OpenMAX AL
Android native multimedia handling is based on Khronos Group OpenMAX AL 1.0.1 API.
The standard OpenMAX AL headers and contain the declarations necessary for performing multimedia output from the native side of Android.
The NDK distribution of OpenMAX AL also provides Android-specific extensions. For information about these extensions, see the comments in OpenMAXAL_Android.h .
The system library libOpenMAXAL.so implements the public native multimedia functions. To link against this library, include the following line in your Android.mk file:
For more information about this topic, see $NDK/docs/openmaxal/index.html , where $NDK is the root directory of your NDK installation.
OpenSL ES
OpenSL ES support for this Android API level adds PCM support. For more information about OpenSL ES support in the NDK, see OpenSL ES.
Android API level 18
The NDK provides the following APIs for developing native code that runs on Android 4.3 system images and above.
OpenGL ES 3.0
The standard OpenGL ES 3.0 headers gl3.h and gl3ext.h contain the declarations needed for performing OpenGL ES 3.0 rendering calls from native code. These rendering calls provide the ability to use the GLSL language to define and use vertex and fragment shaders.
To use OpenGL ES 3.0, link your native module against /system/lib/libGLESv3.so by including the following line in your Android.mk file:
Not all devices support OpenGL ES 3.0. An app can query the OpenGL ES version string and extension string to determine whether the current device supports the features it needs. For information on how to perform this query, see the description of glGetString() in the OpenGL specification.
Additionally, you must put a tag in your manifest file to indicate which version of OpenGL ES your application requires. For more information about the OpenGL ES settings for , see OpenGL ES.
The gles3jni sample application provides a basic example of how to use OpenGL ES 3.0 with the NDK.
Note: The Android emulator does not support OpenGL ES 3.0 hardware emulation. Running and testing code that uses this API requires a real device with hardware that can support OpenGL ES 3.0.
Android API level 21
The NDK provides the following APIs for developing native code that runs on Android 4.3 system images and above.
OpenGL ES 3.1
The standard OpenGL ES 3.1 headers gl31.h and gl3ext.h contain the declarations needed for performing OpenGL ES 3.1 rendering calls from native code. These rendering calls provide the ability to use the GLSL language to define and use vertex and fragment shaders.
To use OpenGL ES 3.1, link your native module against /system/lib/libGLESv3.so by including the following line in your Android.mk file:
Not all devices support OpenGL ES 3.1. An app can query the OpenGL ES version string and extension string to determine whether the current device supports the features it needs. For information on how to perform this query, see the description of glGetString() in the OpenGL specification.
Additionally, you must put a tag in your manifest file to indicate which version of OpenGL ES your application requires. For more information about the OpenGL ES settings for , see OpenGL ES.
The gles3jni sample application provides a basic example of how to use OpenGL ES 3.1 with the NDK.
Note: The Android emulator does not support OpenGL ES 3.1 hardware emulation. Running and testing code that uses this API requires a real device with hardware that can support OpenGL ES 3.1.
Источник