- Install and configure the NDK and CMake
- Install NDK and CMake automatically
- Install the NDK and CMake
- Configure a specific version of CMake
- Groovy
- Kotlin
- Install a specific version of the NDK
- Configure specific versions of the NDK in your project
- Groovy
- Kotlin
- Default NDK version per AGP version
- Setting Up NDK In Android Studio
- Versions used in the guide:
- Downloading The NDK
- Configuring An Old Project
- Create a Native Library
- Create a CMake File
- Link Gradle With Your Native Library
- Writing Native Methods
- 3 Replies to “Setting Up NDK In Android Studio”
- Интеграция Android Studio, Gradle и NDK
- Интегрируем .so файлы в APK
- Строим один APK на архитектуру и добиваемся успеха!
- Автоматически устанавливаем различные коды версий для ABI-зависимых APK
- Работа с ndk в Android Studio
- Мой пример файла .gradle
- Устранение неисправностей
- Получение информации по интеграции NDK
Install and configure the NDK and CMake
To compile and debug native code for your app, you need the following components:
- The Android Native Development Kit (NDK): a set of tools that allows you to use C and C++ code with Android.
- CMake: an external build tool that works alongside Gradle to build your native library. You do not need this component if you only plan to use ndk-build.
- LLDB: the debugger Android Studio uses to debug native code. By default, LLDB will be installed alongside Android Studio.
This page describes how to install these components automatically, or by using Android Studio or the sdkmanager tool to download and install them manually.
Install NDK and CMake automatically
Android Gradle Plugin 4.2.0+ can automatically install the required NDK and CMake the first time you build your project if their licenses have been accepted in advance. If you’ve already read and agree to the license terms, then you can pre-accept the licenses in scripts with the following command:
Install the NDK and CMake
When you install the NDK, Android Studio selects the latest available NDK. For most projects, installing this default version of the NDK is sufficient. If your project needs one or more specific versions of the NDK, though, you can download and configure specific versions. Doing so helps you ensure reproducible builds across projects that each depend on a specific version of the NDK. Android Studio installs all versions of the NDK in the android-sdk /ndk/ directory.
To install CMake and the default NDK in Android Studio, do the following:
With a project open, click Tools > SDK Manager.
Click the SDK Tools tab.
Select the NDK (Side by side) and CMake checkboxes.
Figure 1: The SDK Tools window showing the NDK (Side by side) option
Click OK.
A dialog box tells you how much space the NDK package consumes on disk.
Click OK.
When the installation is complete, click Finish.
Your project automatically syncs the build file and performs a build. Resolve any errors that occur.
Configure a specific version of CMake
The SDK Manager includes the 3.6.0 forked version of CMake and version 3.10.2. Projects that don’t set a specific CMake version are built with CMake 3.10.2. To set the CMake version, add the following to your module’s build.gradle file:
Groovy
Kotlin
If you want to use a CMake version that is not included by the SDK Manager, follow these steps:
- Download and install CMake from the official CMake website.
- Specify the CMake version you want Gradle to use in your module’s build.gradle file.
Either add the path to the CMake installation to your PATH environment variable or include it in your project’s local.properties file, as shown. If Gradle is unable to find the version of CMake you specified in your build.gradle file, you get a build error.
If you don’t already have the Ninja build system installed on your workstation, go to the official Ninja website, and download and install the latest version of Ninja available for your OS. Make sure to also add the path to the Ninja installation to your PATH environment variable.
Install a specific version of the NDK
To install a specific version of the NDK, do the following:
With a project open, click Tools > SDK Manager.
Click the SDK Tools tab.
Select the Show Package Details checkbox.
Select the NDK (Side by side) checkbox and the checkboxes below it that correspond to the NDK versions you want to install. Android Studio installs all versions of the NDK in the android-sdk /ndk/ directory.
Figure 2: The SDK Tools window showing the NDK (Side by side) options
Click OK.
A dialog box tells you how much space the NDK package(s) consumes.
Click OK.
When the installation is complete, click Finish.
Your project automatically syncs the build file and performs a build. Resolve any errors that occur.
Configure each module with the version of the NDK you want it to use. When using Android Studio 3.6 or higher, if you do not specify the version, the Android Gradle plugin chooses a version that it is known to be compatible with.
Configure specific versions of the NDK in your project
You may need to configure the version of the NDK in your project if one of the following is true:
- Your project is inherited and you need to use specific versions of the NDK and the Android Gradle plugin (AGP). For more information, see Configure the NDK for the Android Gradle plugin.
You have multiple versions of the NDK installed and you want to use a specific one. In this case, specify the version using the android.ndkVersion property in the module’s build.gradle file, as shown in the following code sample.
Groovy
Kotlin
Default NDK version per AGP version
Before release, each AGP version is thoroughly tested with the latest stable NDK release at that time. For AGP version 3.6 and above, that NDK version will be used to build your projects if you do NOT specify an NDK version in the build.gradle file. The default NDK version is documented inside the AGP release notes. The current default NDK versions are listed in the following table:
Android Studio/Gradle Plugin Version | |||||||
---|---|---|---|---|---|---|---|
7.0 | 4.2 | 4.1 | 4.0 | 3.6 | 3.5 | 3.4 | |
Default NDK version specified for the version of AGP | 21.4.7075529 | 21.4.7075529 | 21.1.6352462 | 21.0.6113669 | 20.0.5594570 | No default specified |
Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates.
Источник
Setting Up NDK In Android Studio
This guide will help show you how to easily add Android Studio’s NDK to your previous projects. Specifically, it will show you the bare bones setup of the NDK, and get you writing native methods as quick as possible. This guide assumes you know your way around Android Studio.
Versions used in the guide:
- Android Studio 2.3
- NDK 14.0.3770861
- CMake 3.4.1
- LLDB 2.3
Downloading The NDK
Unfortunately, this step will probably be the longest, unless you have already downloaded the NDK. Also a quick tip, be sure to occasionally check the download progress, as you may need handle an unexpected dialog. Nothing is like coming back to your computer 5 hours later, and finding the download has halted because it is waiting for you to answer a question.
So to start, open Android Studio then open the SDK Manager (Tools > Android > SDK Manager).
Open the SDK Tools tab, then check CMake, LLDB, and NDK, and hit apply.
Configuring An Old Project
Once downloaded, the fastest way to configure a NDK project would be to create a new project and include native support from the setup wizard. However, if you have an older project and want to use it instead, configuration is still fairly simple.
Create a Native Library
To make a native library Navigate to Project > app > src > main and create a directory called “cpp”. After, create a new file called “native-lib.cpp” and place it in the “cpp” directory. Just to note, you can name the file anything you want, but for the sake of this guide it’s best to use the same name.
Create a CMake File
CMake is the tool that builds your native library, and needs a Cmake build script. To make the build script, navigate to the Project > app directory and create a text file called “CMakeLists.txt”. Add the following code to the file:
Link Gradle With Your Native Library
Open the module level Gradle build file located in Project > app > build.gradle, then add the code below, and re-sync.
Then execute Build > Refresh Linked C++ Projects.
Writing Native Methods
Now for the fun part, actually writing some code! Don’t get too excited just yet because native methods for Android are a bit trickier than in Java, and much less convenient. Hooray!
First, any Java class that accesses a native function needs to include that library. Add the following to your Java class:
Also, you must declare the native function prototypes, which are any functions you want to call from within your Java class. Add the following to your Java class:
Now you are ready to interact with native code, and can call the function just as you would in Java. For this function, the Java code would look something like this:
Here is the native code for the function shown above. Go to your .cpp file and add the following to it:
You’ll notice that the function name in the example is very long, which is required for your Java class to access it. Not all functions need to be like that, but it does for the ones that Java accesses. Basically the structure for most functions are as follows:
Keep in mind, only the class specified can get access to the function, so it is probably best to create a reusable Java class that handles all native functions to keep from having repeat code.
3 Replies to “Setting Up NDK In Android Studio”
I am trying to do this but this is not working. What i do now ?
Источник
Интеграция Android Studio, Gradle и NDK
Интегрируем .so файлы в APK
Если вы используете Android Studio, то для интеграции нативных библиотек в приложение раньше было необходимо применение различных сложных способов, включая maven и пакеты .aar/.jar … Хорошая новость состоит в том, что теперь этого уже не требуется.
Вам только требуется положить .so библиотеки в каталог jniLibs в поддиректории, названные соответственно каждой поддерживаемой ABI (x86, mips, armeabi-v7a, armeabi) – и всё! Теперь все файлы .so будут интегрированы в APK во время сборки:
Если название папки jniLibs вас не устраивает, вы можете задать другое расположение в build.gradle:
Строим один APK на архитектуру и добиваемся успеха!
Построить один APK на архитектуру очень просто с использованием свойства abiFilter.
По умолчанию ndk.abiFilter(s) имеет значение all. Это свойство оказывает влияние на интеграцию .so файлов, а также на обращения к ndk-build (мы поговорим об этом в конце поста).
Давайте внесем некоторые архитектурные особенности (конфигурации) в build.gradle:
А затем синхронизируем проект с файлами gradle:
Теперь вы можете наслаждаться новыми возможностями, выбирая желаемые варианты сборки:
Каждый из этих вариантов даст вам APK для выбранной архитектуры:
Полный (Release|Debug) APK будет все еще содержать все библиотеки, как и стандартный пакет, упомянутый в начале этого поста.
Но не прекращайте читать на этом месте! Архитектурно-зависимые APK удобны при разработке, но если вы хотите залить несколько из них в Google Play Store, вам необходимо установить различный versionCode для каждого. Сделать это с помощью новейшей системы сборки очень просто.
Автоматически устанавливаем различные коды версий для ABI-зависимых APK
Свойство android.defaultConfig.versionCode отвечает за versionCode для вашего приложения. По умолчанию оно установлено в -1 и, если вы не измените это значение, будет использован versionCode, указанный в файле AndroidManifest.xml.
Поскольку мы хотим динамически изменять наш versionCode, сначала необходимо указать его внутри build.gradle:
Однако все еще возможно хранить эту переменную в AndroidManifest.xml, если вы получаете ее «вручную» перед изменением:
Теперь вы можете использовать versionCode с различными модификаторами:
Здесь мы поставили префикс 6 для x86, 4 для mips, 2 для ARMv7 и 1 для ARMv5.
Работа с ndk в Android Studio
Если в исходниках проекта есть папка jni, система сборки попытается вызвать ndk-build автоматически.
В текущей реализации ваши Android.mk мейкфайлы игнорируются, вместо них создается новый на лету. Это действительно удобно для небольших проектов (вам больше вообще не требуются .mk файлы!), но в больших может раздражать, если вам требуются все возможности, предоставляемые мейкфайлами. Существует возможность отключить это свойство в build.gradle:
Если вы хотите использовать генерируемый на лету мейкфайл, вы можете настроить его изначально, установив свойство ndk.moduleName, например, так:
Вы также можете установить другие свойства ndk:
- cFlags,
- ldLibs,
- stl (т.е.: gnustl_shared, stlport_static …),
- abiFilters (т.е.: «x86», «armeabi-v7a»).
Генерация отладочного APK достигается заданием значения true для свойства android.buildTypes.debug.jniDebugBuild; в этом случае ndk-build будет передано NDK_DEBUG=1.
Если вы используете RenderScript из NDK, вам потребуется установить значение true для свойства defaultConfig.renderscriptNdkMode.
Если вы доверяете авто-генерируемым мейкфайлам, то можете задавать различные cFlags в зависимости от конечной архитектуры, когда вы собираете многоархитектурные APK. Так что если вы хотите полностью довериться gradle, мы рекомендуем генерировать различные APK для архитектур, используя ранее описанные модификаторы конфигурации:
Мой пример файла .gradle
Соединяя все вместе, привожу файл build.gradle, который сам сейчас использую. В нем нет модификаторов для различных поддерживаемых ABI, он не использует интеграцию с ndk-build, поэтому работает в Windows окружении и не требует ни изменения обычных мест расположения исходников и библиотек, ни содержимого моих .mk файлов.
Устранение неисправностей
NDK не сконфигурирован
Если вы получаете ошибку:
Это означает, что инструменты не найдены в каталоге NDK. Имеется два выхода: установить переменную ANDROID_NDK_HOME в соответствии с вашим каталогом NDK и удалить local.properties или же установить ее вручную внутри local.properties:
Не существует правила для создания цели
Если вы получаете ошибку:
Ее причиной может быть имеющаяся ошибка в NDK для Windows, когда имеется только один исходный файл для компилирования. Добавьте еще один пустой файл – и все заработает.
Прочие вопросы
Вы, возможно, сможете найти ответы на интересующие вас вопросы в google группе adt-dev.
Получение информации по интеграции NDK
Лучшее место для нахождения более подробной информации – официальная страница проекта.
Посмотрите на список изменений и, если пролистаете его целиком, найдете примеры проектов, связанных с интеграцией NDK, внутри самых свежих архивов gradle-samples-XXX.zip.
На видео ниже показано, как настроить проект с исходниками NDK из Android Studio.
Источник