Время на прочтение25 мин
Количество просмотров224K
На днях я обнаружил, что версия Android Studio неуклонно стремится к единице, в связи с чем задумался об изучении этого инструмента. Чтобы не было скучно, я решил поделиться своим опытом и собранными граблями в виде статьи-туториала.
Сразу хочу оговориться, что я не являюсь гуру Android-разработки, поэтому каких-либо откровений в тексте вы не найдете. Зато тут есть пошаговая инструкция по установке и настройке Android Studio под Windows и созданию простейшего проекта с использованием Android NDK.
Также заранее предупреждаю: статья получилась большой и очень подробной (честно, сам не ожидал), даже несмотря на то, что я почти все скриншоты и некоторые листинги кода спрятал под спойлеры.
На момент написания последней версией Android Studio была 0.8.1, для последующих версий необходимые действия могут отличаться от нижеописанных (очень надеюсь, что в лучшую сторону).
Для тех, кого интересует только NDK
Для тех, кого интересуют только настройки Gradle для NDK
Установка и настройка Android Studio
1. Необходимо установить JDK (Java Development Kit) и JRE (Java Runtime Environment).
Раньше Android SDK поддерживал только JDK версии 6, но теперь это в прошлом. Поддерживается 7 и даже 8 (по крайней мере, именно 8-ю версию я указал в качестве JAVA_HOME и в настройках Android Studio, и никаких проблем не испытал).
JRE же нужен для запуска самой студии. У меня она использует версию 7.
Скачать JDK и JRE версий больше 6 можно с сайта Oracle.
Переменную JAVA_HOME теперь, вроде бы, можно не устанавливать, так как в Android Studio мы будем в настройках прописывать путь к JDK. Но я ее установил. Для этого нужно:
- Зайти в Панель управления\Система и безопасность\Система, выбрать слева Дополнительные параметры системы, в открывшемся диалоге найти кнопку Переменные среды.
- Создать системную или пользовательскую переменную JAVA_HOME и указать для нее путь к JDK. У меня указан вот такой путь: C:\Program Files\Java\jdk1.8.0_05.
Если вы по каким-либо причинам нуждаетесь в 6 версии JDK
JDK 6 без регистрации можно получить так:
- Скачать Java EE 6 с сайта Oracle.
- Установить его. В комплекте есть JDK 6.
- В качестве JAVA_HOME в этом случае нужно указать путь к JDK из Java EE, по умолчанию это C:/glassfish3/jdk.
2. Если у вас установлен Android SDK.
В комплекте с Android Studio идет свой Android SDK. И, если вы хотите использовать именно его, то в некоторых случаях может случиться странное. Например, у меня при обновлении SDK через SDK Manager часть файлов записывалась в старую папку, и возникли проблемы, когда я эту папку удалил. Скорее всего это произошло из-за того, что в реестре хранился ключ с путем к старой папке. Поэтому имеет смысл почистить реестр. Для этого нужно запустить regedit.exe и найти HKEY_LOCAL_MACHINE\Software\Android SDK Tools для 32-битных машин либо HKEY_LOCAL_MACHINE\Software\Wow6432Node\Android SDK Tools для 64-битных машин и удалить Android SDK Tools. Если в реестре вашей системы таких ключей нет, то все в порядке.
Если у вас установлена переменная среды ANDROID_SDK_HOME и вы хотите, чтобы она указывала на старую установку, то, по идее, это не должно стать проблемой, так как при настройке Android Studio мы укажем ей путь к SDK. Проблемы могут возникнуть, если эту переменную использует какое-либо из приложений, входящих в состав Android SDK.
3. Теперь переходим к установке Android Studio.
Нужно скачать Android Studio для вашей системы с официальной страницы и установить ее. По умолчанию, если выбрать «Установить только для меня» ставится в \Users\<user>\AppData\Local\Android\android-studio\, иначе ставится в \Program FIles (x86)\Android\android-studio\. Можно выбрать и другую папку.
После установки запускаем Android Studio.
Видим вот такой диалог
В нем делаем следующее:
- Проверяем обновления и, при необходимости, обновляемся (для этого нажмите на Check в нижней части окна)
- Заходим в Configure->SDK Manager (на всякий случай: SDK Manager — это не часть Android Studio, а утилита из Android SDK) и устанавливаем то, что вам необходимо. Если вы не знаете, что необходимо, то лучше установить все, что он предложит.
Вот что он установил у меня
- Затем я сменил тему на Darcula.
Как это сделать
нужно зайти в Configure->Settings->Appearance:
- Далее заходим в Configure->Project Defaults->Project Structure и меняем SDK Location на путь к вашему Android SDK, а JDK Location на путь к JDK.
Скриншот
Создание проекта
1. New Project
Жмем New Project.
Появляется вот такой диалог
В нем можно настроить:
- Имя проекта (я оставил по умолчанию: My Application)
- Домен компании, по умолчанию <username>.example.com, в моем случае markedone.example.com
- Имя пакета тоже можно отредактировать, нажав на Edit справа. По умолчанию генерируется из имени проекта и домена компании и выглядит как com.example.<username>.<имя проекта в lowercase без пробелов>, я его изменил на com.example.markedone.myapp.
- Путь, куда будет сохранен проект. Я указал свою папку для всяких тестовых проектов.
Когда все введено, жмем Next.
2. Form Factors
В этом диалоге выбираем целевые платформы и API.
Диалог выглядит так
Здесь я все оставил по умолчанию: Phone and Tablet и 4.0.3 IceCreamSandwich. Если API для каких-то платформ не установлен, выдается сообщение Not Insatlled. Например, как видно на скриншоте, у меня не установлены библиотеки для Google Glass (сделать это можно через SDK Manager).
Также обратите внимание на Help me choose, прикольная штука
Если нажать Help me choose, то откроется вот такой интересный диалог
Он содержит информацию по охвату устройств при выборе той или иной версии API. Прямоугольники версий API кликабельны, справа будет выведен список доступного в них функционала. Например, для предлагаемого по умолчанию Ice Cream Sandwich’а:
Жмем Next.
3. Add Activity
На следующем экране нам предлагается выбрать Activity
Естественно, я не смог пройти мимо Fullscreen Activity и выбрал ее. Вы можете выбрать другую Activity, но в этом случае у нас будут отличаться исходники на Java, и вам придется самостоятельно добавлять вызов нативного метода из Java (впрочем, в этом нет ничего сложного).
Делаем выбор, нажимаем Next.
Появляется следующий диалог
Здесь нам предлагается настроить Activity.
- Activity Name — имя класса, я оставил по умолчанию: FullscreenActivity.
- Layout Name — имя layout, для редактора UI, также оставляем по умолчанию.
- Title — по умолчанию предлагается FullscreenActivity, я поставил пробел: Fullscreen Activity.
Нажимаем Finish.
В итоге должен открыться проект
Сборка и запуск
1. Сборка проекта
Запускаем сборку через меню: Build->Make Project (для пунктов меню указаны иконки и горячие клавиши, так что с ними будет несложно разобраться).
У меня при первой сборке возникла ошибка:
Произошло это в файле MyApplication/app/build.gradle
Для того, чтобы понять в чем дело, достаточно навести курсор на подчеркнутую строку:
Все просто, здесь указана версия 19, а у нас установлена только 20, да и в настройках проекта мы указали 20 как целевую. Просто поменяем цифру:
Как видно, студия на этом не успокоилась, и предлагает установить еще более новую версию. Но нам сейчас это не нужно.
Снова запускаем Build->Make Project. На этот раз у меня все собралось. Надеюсь, у вас тоже.
2. Настройка виртуального устройства
Для того чтобы запустить программу в эмуляторе, нужно настроить виртуальное устройство. Заходим в Tools->Android->AVD Manager (это, как и SDK Manager, утилита из Android SDK). Нам нужна первая вкладка, Android Virtual Device, она и открыта по умолчанию. Справа находим кнопку Create… и нажимаем ее.
Появится диалог настройки виртуального устройства
- AVD Name — имя виртуального устройства, я ввел TestPhone. Дальше я, правда, выбрал планшет, но уже не стал менять название.
- Device — различные предустановленные настройки устройства, значение выбирается из доступных в выпадающем списке, я выбрал 7» WSVGA (Tablet) (1024 x 600: mdpi).
- Target — целевая версия API, доступны только те, которые есть в SDK. Установить их можно через SDK Manager.
W в названии означает Wear, версия для носимых устройств (часы и прочее). Так как мы в настройках проекта выбирали Tablet&Phone, то нам нужен другой пункт: Android L (Preview) — API Level L.
- CPU/ABI — платформа, я выбрал ARM (armeabi-v7a).
- Keyboard — тут, думаю, все понятно.
- Skin — как я понял, внешний вид устройства, я выбрал значение, соответствующее установленному значению Device: WSVGA.
- Front Camera и Back Camera — наличие камер.
- Memory Options — оперативная память.
- Internal Storage — жесткий диск устройства.
- SD Card — думаю, понятно.
- Emulation options: Snapshot — позволяет эмулятору сохранять свое состояние между запусками, Use Host GPU — позволяет использовать видеокарту компьютера для OpenGL ES. Последнюю опцию я включил, но OpenGL — приложение у меня впоследствии упало на этом эмуляторе при старте. Наверное, из-за ARM vs x86_64.
Внизу диалога выводится, какую ошибку вы допустили при настройке. Например, в имени устройства нельзя вводить пробелы, а некоторые поля обязательны для заполнения. Когда внизу нет надписи — все введено верно. Жмем OK.
Устройство появилось в списке
Пара слов о вкладке Device Definitions
На ней заданы доступные устройства (те, которые потом отображаются в выпадающем списке Device при создании нового виртуального устройства). Чтобы создать новое устройство, нужно нажать на кнопку Create Device… и озаботиться заполнением следующего диалога:
Закрываем AVD Manager и возвращаемся в главное окно Android Studio.
3. Запуск на эмуляторе
Выполняем Run->Run ‘app’.
Придется подождать, пока произойдет сборка проекта для запуска.
В конце концов, появится окно выбора устройства
Здесь единственный доступный вариант для выбора — это наше виртуальное устройство. Он нам сразу предложен, так что просто жмем OK.
Запускается эмулятор, довольно долго
Можно открыть Tools->Android->Android Device Monitor (утилита из Android SDK), чтобы увидеть логи с эмулятора. Он должен автоматически подцепить виртуальное устройство и сразу начать выводить лог.
Android Device Monitor
А вот приложение после запуска эмулятора у меня с первого раза не открылось, пришлось еще раз нажать Run->Run ‘app’.
Появился немного изменившийся диалог
Здесь устройство перекочевало из списка для запуска в список уже запущенных. В этом списке, само собой, оказываются и реальные устройства.
После этого дело пошло, и приложение довольно быстро установилось и запустилось.
Полноэкранный режим
А если на приложение тапнуть, то выглядит оно так
Это не поведение системы, обработка клика происходит в приложении (файл FullscreenActivity.java):
// Set up the user interaction to manually show or hide the system UI.
contentView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
После запуска, Android Studio предложила мне выключить Android Device Monitor, для того чтобы интегрировать вывод прямо в IDE.
Вот как выглядит интеграция
4. Запуск в Debug-режиме
Run->Debug ‘app’
Снова уже знакомый нам диалог
Жмем OK.
Ждем, пока запустится приложение и приконнектится дебаггер. Я поставил точку останова при нажатии на кнопку Dummy Button.
Android Studio в дебаге
Немного раздражает отсутствие панельки со всякими Step Into, Step Out etc.
Все это находится в меню Run
5. Запуск на 4.0.3
В процессе создания и запуска проекта вы, наверное, заметили, что мы создали приложение, совместимое с версией 4.0.3, но запускали его только на самой последней версии Android. Сейчас мы это исправим. Для этого нужно установить версию 4.0.3 через Tools->Android->SDK Manager.
Необходимое отмечено галочками на скриншоте
Это SDK Platform, ARM EABI v7a System Image и Intel x86 Atom System Image. На самом деле, мы запускали эмулятор ARM, и Intel нам сейчас ставить не обязательно. Я его поставил сугубо потому, что он установлен и для Android L.
Теперь создадим еще одно устройство для новой старой версии Android (или же вы можете отредактировать старое).
Настройки нового устройства
Запускаем (Run->Run ‘app’).
В диалоге выбираем новое устройство для запуска
И смотрим, как выглядит новый эмулятор — явно брутальнее.
Запуск
Полноэкранный режим
После нажатия
5. Запуск на устройстве
Перед тем как перейти к работе с NDK, давайте запустим проект на реальном устройстве. Я буду запускать на телефоне
Huawei Ascend G300 с Android 4.0.3
Первое, что нужно сделать, это установить adb-драйвер. У меня с этим все довольно просто, драйвер находится прямо на телефоне, единственное, что нужно сделать, это воткнуть шнур в компьютер, зайти в примонтировавшийся диск и запустить исполняемый файл, который и установит adb-драйвер. Для других устройств все может быть сложнее. Например, для планшета Prestigio мне в свое время пришлось прописывать Vendor ID в специальный файл (чтобы использовался стандартный драйвер от Google), для Samsung нужен их собственный Kies, был отдельный драйвер для HTC и так далее. В общем, вам придется самостоятельно разобраться, как установить драйвер для вашего устройства.
После того как драйвер был установлен, нужно на устройстве разрешить отладку по USB. У меня на телефоне для этого нужно зайти в Настройки->Для разработчиков->Отладка по USB. Но для разных устройств, а также сборок и версий Android, расположение этого пункта меню может отличаться.
Теперь телефон будет находиться Android SDK, а разрабатываемые приложения будут устанавливаться. Однако, для Huawei это еще не все: с телефона не идут логи, нужно их включить.
Как включить логи на Huawei
Набрать в качестве телефонного номера: *#*#2846579#*#*
Появится сервисное меню.
Перейти в ProjectMenu->Background Setting->Log Setting
Открыть Log switch и установить там ON.
Открыть Log level setting и установить необходимый вам уровень логирования (я поставил verbose).
Перезагрузить телефон.
Теперь можно запускать приложение на устройстве: Run->Run ‘app’
В диалоге выбора устройства появилось реальное устройство
Запускаемся на телефоне.
Результат запуска.
Приложение в портрете:
Приложение в ландшафте:
Установка и настройка Android NDK
1. Установка NDK
Android SDK, как мы уже выяснили, входит в комплект Android Studio, а вот NDK — нет. Скачиваем NDK, подходящий для вашей системы, отсюда. Распаковываем архив и кладем в какую-нибудь папку, например, в D:\ndk, так, чтобы файл ndk-build.cmd лежал прямо в ней. Важно: необходимо, чтобы в пути к NDK не было пробелов.
2. Добавим переменную ANDROID_NDK_HOME
Заходим в Панель управления\Система и безопасность\Система, выбираем слева Дополнительные параметры системы, в открывшемся диалоге нажимаем кнопку Переменные среды. Создаем переменную с именем ANDROID_NDK_HOME и значением D:\ndk (путь к вашей NDK).
Альтернативно, вместо указания глобальной переменной можно прописать путь к ndk в файле local.properties вашего проекта (прямо в корневой папке: MyApplication\local.properties). Содержимое файла будет выглядеть примерно так (обратите внимание на двойные бэкслеши, так как для Windows это критично):
## This file is automatically generated by Android Studio.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file should *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
sdk.dir=C:\\Users\\<user>\\AppData\\Local\\Android\\android-studio\\sdk
ndk.dir=D:\\ndk
Не верьте дисклеймеру про «ваши изменения будут выкинуты», в данном случае это не так. Обратите внимание, что этот файл рекомендуется исключать из-под контроля версий, так как он содержит только локальную для пользователя информацию. Для разнообразия в этом нам не соврали. Ну и, само собой, это изменение никак не повлияет на другие Ваши проекты. При установленной ANDROID_NDK_HOME прописывать путь в local.properties необязательно.
3. Установим необходимую версию Android API
Зайдите в NDK\platforms (у меня это D:\ndk\platforms) и посмотрите максимальную версию доступных API. В моем случае максимальная версия 19. Но при этом в SDK у нас установлены только версии 20 и 15. Так что заходим в SDK Manager и скачиваем SDK Platform версии 19, иначе ничего не соберется.
Что надо скачать
4. Настроим gradle для работы с NDK
Информацию я брал из сэмплов, скачать их можно здесь, в самом низу страницы. Я скачивал сэмплы для версии 0.11. В качестве основного примера я брал ndkSanAngeles.
Как запустить ndkSanAngeles
После того, как сэмплы скачаны, их нужно распаковать. Затем нужно открыть проект ndkSanAngeles. Для Android Studio проектом является папка, так что открывать надо именно ее. Для того этого выполняем File->Open, либо, если вы в Welcome диалоге, Open Project. Ищем папку ndkSanAngeles через диалог открытия файла.
После открытия проекта стоит обратить взор на файл build.gradle. Вот его оригинал:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.11.0'
}
}
apply plugin: 'android'
android {
compileSdkVersion 19
buildToolsVersion '19.1.0'
defaultConfig {
ndk {
moduleName "sanangeles"
cFlags "-DANDROID_NDK -DDISABLE_IMPORTGL"
ldLibs "GLESv1_CM", "dl", "log"
stl "stlport_static"
}
// This actual the app version code. Giving ourselves 1,000,000 values
versionCode = 123
}
buildTypes.debug.jniDebugBuild true
productFlavors {
x86 {
ndk {
abiFilter "x86"
}
// this is the flavor part of the version code.
// It must be higher than the arm one for devices supporting
// both, as x86 is preferred.
versionCode = 3
}
arm {
ndk {
abiFilter "armeabi-v7a"
}
versionCode = 2
}
mips {
ndk {
abiFilter "mips"
}
versionCode = 1
}
fat {
// fat binary, lowest version code to be
// the last option
versionCode = 0
}
}
// make per-variant version code
applicationVariants.all { variant ->
// get the single flavor
def flavorVersion = variant.productFlavors.get(0).versionCode
// set the composite code
variant.mergedFlavor.versionCode = flavorVersion * 1000000 + defaultConfig.versionCode
}
}
А вот измененная версия, чтобы проект собирался у меня:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.12.+'
}
}
apply plugin: 'android'
android {
compileSdkVersion 19
buildToolsVersion '20.0.0'
defaultConfig {
ndk {
moduleName "sanangeles"
cFlags "-DANDROID_NDK -DDISABLE_IMPORTGL"
ldLibs "GLESv1_CM", "dl", "log"
stl "stlport_static"
}
// This actual the app version code. Giving ourselves 1,000,000 values
versionCode = 123
}
buildTypes.debug.jniDebugBuild true
productFlavors {
x86 {
ndk {
abiFilter "x86"
}
// this is the flavor part of the version code.
// It must be higher than the arm one for devices supporting
// both, as x86 is preferred.
versionCode = 3
}
arm {
ndk {
abiFilter "armeabi-v7a"
}
versionCode = 2
}
mips {
ndk {
abiFilter "mips"
}
versionCode = 1
}
fat {
// fat binary, lowest version code to be
// the last option
versionCode = 0
}
}
// make per-variant version code
applicationVariants.all { variant ->
// get the single flavor
def flavorVersion = variant.productFlavors.get(0).versionCode
// set the composite code
variant.mergedFlavor.versionCode = flavorVersion * 1000000 + defaultConfig.versionCode
}
}
Изменения следующие:
- О несовпадении версии плагина gradle (classpath ‘com.android.tools.build:gradle:0.11.0’) будет сказано при попытке сборки и предложен правильный номер версии. У меня это 0.12.+.
- compileSdkVersion 19 остается, так как это максимальная версия для текущего NDK.
- buildToolsVersion изменился на 20. Установленные версии можно посмотреть в SDK Manager, там же можно установить другие.
После этого ndkSanAngeles должен собраться. Будьте внимательны, проверяйте версии, установленные у вас.
В нашем проекте нужно выбрать правильный файд build.gradle, так как здесь их два. Дело в том, что MyApplication — это проект, а app — это модуль проекта (или подпроект), и у них build.gradle для каждого свой. Сначала рассмотрим файл проекта
MyApplication->build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.12.+'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
Из комментариев в коде явно следует, что нам нужен файл модуля
MyApplication->app->build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 20
buildToolsVersion "20.0.0"
defaultConfig {
applicationId "com.example.markedone.myapp"
minSdkVersion 15
targetSdkVersion 20
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
// You must install or update the Support Repository through the SDK manager to use this dependency.
//compile 'com.android.support:support-v4:19.+'
compile 'com.android.support:support-v4:20.+'
}
Настроим его для работы с NDK, используя в качестве «донора» build.gradle из ndkSanAngeles.
Для начала, заменим
compileSdkVersion 20
на
compileSdkVersion 19
так как NDK ограничен версией 19.
В defaultConfig мы добавим настройки ndk, а также заменим targetSdkVersion на 19:
defaultConfig {
applicationId "com.example.markedone.myapp"
minSdkVersion 15
targetSdkVersion 19
versionCode 1
versionName "1.0"
ndk {
moduleName "myapp"
cFlags "-DANDROID_NDK"
ldLibs "log"
stl "stlport_static"
}
}
Настройки NDK включают в себя
- moduleName — имя модуля, будет использовано для именования *.so файла
- cFlags — флаги C
- ldLibs — библиотеки, которые вы хотите подключить к нативному коду
- stl — версия библиотеки STL
В buildTypes включим для debug дебажную сборку JNI:
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug.jniDebugBuild true
}
Теперь добавим productFlavors. Здесь мы указываем, какие собранные *.so библиотеки включать в сборку под конкретную архитектуру. Таким образом, *.apk собранный для arm будет содержать версию библиотеки только для arm, под x86 — для x86 и так далее. Этот кусок полностью скопирован с ndkSanAngeles. Объяснение значений versionCode из комментариев: для x86 ставим максимальное значение versionCode, так как если устройство поддерживает и x86 и arm, то сборка x86 предпочтительнее (видимо, так как у нее большая версия, то установлена будет именно она), а минимальный versionCode прописывается для fat (по идее это должен быть «толстый» *.apk, содержащий сразу все возможные версии библиотек).
productFlavors {
x86 {
ndk {
abiFilter "x86"
}
// this is the flavor part of the version code.
// It must be higher than the arm one for devices supporting
// both, as x86 is preferred.
versionCode = 3
}
arm {
ndk {
abiFilter "armeabi-v7a"
}
versionCode = 2
}
mips {
ndk {
abiFilter "mips"
}
versionCode = 1
}
fat {
// fat binary, lowest version code to be
// the last option
versionCode = 0
}
}
«Собираем» значение versionCode для каждого из вариантов сборки:
// make per-variant version code
applicationVariants.all { variant ->
// get the single flavor
def flavorVersion = variant.productFlavors.get(0).versionCode
// set the composite code
variant.mergedFlavor.versionCode = flavorVersion * 1000000 + defaultConfig.versionCode
}
Наконец, последняя секция, dependencies. Если помните, здесь мы меняли compile ‘com.android.support:support-v4:19.+’ на compile ‘com.android.support:support-v4:20.+’, чтобы собирать с единственной установленной у нас версией библиотеки. Теперь придется поменять обратно на 19.
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
// You must install or update the Support Repository through the SDK manager to use this dependency.
compile 'com.android.support:support-v4:19.+'
}
Полный листинг измененного файла build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 19
buildToolsVersion "20.0.0"
defaultConfig {
applicationId "com.example.markedone.myapp"
minSdkVersion 15
targetSdkVersion 19
versionCode 1
versionName "1.0"
ndk {
moduleName "myapp"
cFlags "-DANDROID_NDK"
ldLibs "log"
stl "stlport_static"
}
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug.jniDebugBuild true
}
productFlavors {
x86 {
ndk {
abiFilter "x86"
}
// this is the flavor part of the version code.
// It must be higher than the arm one for devices supporting
// both, as x86 is preferred.
versionCode = 3
}
arm {
ndk {
abiFilter "armeabi-v7a"
}
versionCode = 2
}
mips {
ndk {
abiFilter "mips"
}
versionCode = 1
}
fat {
// fat binary, lowest version code to be
// the last option
versionCode = 0
}
}
// make per-variant version code
applicationVariants.all { variant ->
// get the single flavor
def flavorVersion = variant.productFlavors.get(0).versionCode
// set the composite code
variant.mergedFlavor.versionCode = flavorVersion * 1000000 + defaultConfig.versionCode
}
sourceSets { main { jni.srcDirs = ['src/main/jni', 'src/main/jni/'] } }
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
// You must install or update the Support Repository through the SDK manager to use this dependency.
compile 'com.android.support:support-v4:19.+'
}
5. Создаем папку jni
В папке jni мы будем сохранять C/C++ файлы. Этого от нас ожидает NDK. Папку нам нужно создать в MyApplication/app/src/main. Это можно сделать прямо из Android Studio, причем, двумя способами.
Во-первых, можно кликнуть правой кнопкой на main и просто создать папку через
New->Directory
Во вторых, можно воспользоваться специальным пунктом меню
New->Folder->JNI Folder
Он запускает визард создания папки
В первом диалоге мы выбираем, для какой части модуля будет создана папка jni, а во втором можно изменить ее расположение.
6. Добавим C++ файлы
Визарда для C++ файлов нет, поэтому для создания файла мы кликаем правой кнопкой на папке jni и выбираем
New->File
Для начала создадим заголовочный файл myapp.h:
#pragma once
#include <jni.h>
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT jstring JNICALL Java_com_example_markedone_myapp_FullscreenActivity_stringFromJNI(JNIEnv* env, jclass clazz);
#ifdef __cplusplus
}
#endif
Описание
#pragma once
— вместо стандартной (#ifndef/#define/#endif) защиты от повторного включения. Сейчас#pragma once
понимается большинством C++ компиляторов.#include <jni.h>
— включаем заголовок JNI, чтобы можно было использовать типы, объявленные там.#ifdef __cplusplus ... #endif
— код внутри будет скомпилирован только в C++ (но не в C).extern "C" { ... }
— избавляемся от name mangling (что это и почему, хорошо описано тут).JNIEXPORT jstring JNICALL Java_com_example_markedone_myapp_FullscreenActivity_stringFromJNI(JNIEnv* env, jclass clazz);
— объявление функции, которую будем реализовывать.
Разберем это объявление подробнее.- JNIEXPORT необходимо для грамотной линковки.
- JNICALL для правильного соглашения о вызове.
- jstring — тип возвращаемого значения функции, в данном случае это строка, совместимая со строкой Java.
- Java_com_example_markedone_myapp_FullscreenActivity_stringFromJNI — имя функции, состоит из:
Java — язык, который вызывает.
com_example_markedone_myapp — это id приложения (com.example.markedone.myapp).
FullscreenActivity — имя класса Java, который содержит объявление метода, представляющего нативную функцию.
stringFromJNI — собственно, имя функции (таким оно будет в Java). JNIEnv* env, jclass clazz
— обязательные параметры, передающиеся из Java.
JNIEnv* env
— указатель на объект, представляющий из себя JNI-окружение.
jclass clazz
— класс, которому принадлежит объявление нативного метода в Java. Здесь нужно оговориться, что jclass clazz — это для статического нативного (static native) метода. Для нестатического метода будет нужно писатьjobject obj
.
Теперь создадим файл реализации, myapp.cpp. В нем мы напишем следующий код:
#include <android/log.h>
#include <string>
#include "myapp.h"
JNIEXPORT jstring JNICALL Java_com_example_markedone_myapp_FullscreenActivity_stringFromJNI(JNIEnv* env, jclass clazz)
{
std::string tag("GREETING");
std::string message("Hello from C++!");
__android_log_print(ANDROID_LOG_INFO, tag.c_str(), "%s", message.c_str());
std::string jniMessage("Hello from JNI!");
return env->NewStringUTF(jniMessage.c_str());
}
Описание
#include <android/log.h>
— подключаем лог, ради которого мы даже добавили библиотеку (ldLibs «log»)#include - для std::string, который мы используем для проверки наличия STL.
#include "myapp.h"
— подключаем наш заголовочный файл.
JNIEXPORT jstring JNICALL Java_com_example_markedone_myapp_FullscreenActivity_stringFromJNI(JNIEnv* env, jclass clazz) { ... } - реализуем функцию, объявленную в "myapp.h".
std::string tag("GREETING"); std::string message("Hello from C++!");
— создаем строки для вывода в лог.
__android_log_print(ANDROID_LOG_INFO, tag.c_str(), "%s", message.c_str());
— вывод в лог. Обратите внимание, что необходимо указывать 4 параметра: тип сообщения в логе, тэг, формат строки, и, наконец, само сообщение.
std::string jniMessage("Hello from JNI!");
— строка, которую мы будем передавать в Java.
return env->NewStringUTF(jniMessage.c_str());
— возвращаемое значение, при помощи JNIEnv создаем jstring из C-строки. Обратите внимание, что нам не нужна конструкция вида(*env)->
, так как мы пишем на C++, а не на C.
А теперь мы создадим еще один файл: stub.cpp, и оставим его пустым. Дело в том, что если оставить только один *.cpp файл в папке jni, то ndk-build будет выдавать ошибку «no rule to make target».
7. Добавим вызов нативной функции из Java
Открываем файл MyApplication/app/src/main/java/com.example.markedone.myapp.FullscreenActivity. На самом деле, у него расширение java, а com, example, markedone и myapp — это папки, но Android Studio это скрывает.
Содержимое файла
package com.example.markedone.myapp;
import com.example.markedone.myapp.util.SystemUiHider;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* @see SystemUiHider
*/
public class FullscreenActivity extends Activity {
/**
* Whether or not the system UI should be auto-hidden after
* {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = true;
/**
* If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* If set, will toggle the system UI visibility upon interaction. Otherwise,
* will show the system UI visibility upon interaction.
*/
private static final boolean TOGGLE_ON_CLICK = true;
/**
* The flags to pass to {@link SystemUiHider#getInstance}.
*/
private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;
/**
* The instance of the {@link SystemUiHider} for this activity.
*/
private SystemUiHider mSystemUiHider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.fullscreen_content);
// Set up an instance of SystemUiHider to control the system UI for
// this activity.
mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS);
mSystemUiHider.setup();
mSystemUiHider
.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
// Cached values.
int mControlsHeight;
int mShortAnimTime;
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void onVisibilityChange(boolean visible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// If the ViewPropertyAnimator API is available
// (Honeycomb MR2 and later), use it to animate the
// in-layout UI controls at the bottom of the
// screen.
if (mControlsHeight == 0) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == 0) {
mShortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
controlsView.animate()
.translationY(visible ? 0 : mControlsHeight)
.setDuration(mShortAnimTime);
} else {
// If the ViewPropertyAnimator APIs aren't
// available, simply show or hide the in-layout UI
// controls.
controlsView.setVisibility(visible ? View.VISIBLE : View.GONE);
}
if (visible && AUTO_HIDE) {
// Schedule a hide().
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
}
});
// Set up the user interaction to manually show or hide the system UI.
contentView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
findViewById(R.id.dummy_button).setOnTouchListener(mDelayHideTouchListener);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
Handler mHideHandler = new Handler();
Runnable mHideRunnable = new Runnable() {
@Override
public void run() {
mSystemUiHider.hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
}
Добавим следующий код в класс FullscreenActivity:
static {
System.loadLibrary("myapp");
}
private static native String stringFromJNI();
Здесь сначала идет загрузка библиотеки, а затем объявление метода stringFromJNI, который соответствует нашей функции в C++. Обратите внимание, что он объявлен как static (это влияет на то, что (jclass или jobject) будет в качестве второго параметра C++-функции) и native. Реализовывать native-метод не нужно, мы это уже сделали в C++, а остальное за нас сделает JNI.
Теперь мы, в общем-то, уже можем вызвать нашу функцию. Если вы, как и я, выбрали FullscreenActivity, то у нас есть Dummy Button, который, по сути, ничего не делает. И даже уже есть touch listener, пусть и не самый лучший (он будет вызываться много раз, пока палец на экране), но, чтобы не плодить лишний код, используем его.
Для начала добавим в список импорта:
import android.widget.Button;
чтобы можно было нормально работать с кнопкой.
Найдем следующий код:
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
и добавим несколько строк перед return false
.
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
final String message = stringFromJNI();
final Button button = (Button)findViewById(R.id.dummy_button);
final String actualText = button.getText().toString();
if(message.equals(actualText)) {
button.setText("Dummy Button");
}
else {
button.setText(message);
}
return false;
}
};
Описание добавленного кода
final String message = stringFromJNI();
— получаем строку из C++. Вызов нативного метода — то, ради чего все и затевалось.final Button button = (Button)findViewById(R.id.dummy_button);
— находим объект кнопки.final String actualText = button.getText().toString();
— вытаскиваем текущий текст кнопки.if(message.equals(actualText))
— сравниваем строку, полученную из C++, с текстом кнопки.button.setText("Dummy Button");
— если одинаковы, меняем текст кнопки на Dummy Button.button.setText(message);
— если различаются, то меняем на текст, полученный из C++.
Полный листинг класса измененного класса
package com.example.markedone.myapp;
import com.example.markedone.myapp.util.SystemUiHider;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* @see SystemUiHider
*/
public class FullscreenActivity extends Activity {
static {
System.loadLibrary("myapp");
}
private static native String stringFromJNI();
/**
* Whether or not the system UI should be auto-hidden after
* {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = true;
/**
* If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* If set, will toggle the system UI visibility upon interaction. Otherwise,
* will show the system UI visibility upon interaction.
*/
private static final boolean TOGGLE_ON_CLICK = true;
/**
* The flags to pass to {@link SystemUiHider#getInstance}.
*/
private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;
/**
* The instance of the {@link SystemUiHider} for this activity.
*/
private SystemUiHider mSystemUiHider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.fullscreen_content);
// Set up an instance of SystemUiHider to control the system UI for
// this activity.
mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS);
mSystemUiHider.setup();
mSystemUiHider
.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
// Cached values.
int mControlsHeight;
int mShortAnimTime;
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void onVisibilityChange(boolean visible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// If the ViewPropertyAnimator API is available
// (Honeycomb MR2 and later), use it to animate the
// in-layout UI controls at the bottom of the
// screen.
if (mControlsHeight == 0) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == 0) {
mShortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
controlsView.animate()
.translationY(visible ? 0 : mControlsHeight)
.setDuration(mShortAnimTime);
} else {
// If the ViewPropertyAnimator APIs aren't
// available, simply show or hide the in-layout UI
// controls.
controlsView.setVisibility(visible ? View.VISIBLE : View.GONE);
}
if (visible && AUTO_HIDE) {
// Schedule a hide().
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
}
});
// Set up the user interaction to manually show or hide the system UI.
contentView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
findViewById(R.id.dummy_button).setOnTouchListener(mDelayHideTouchListener);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
final String message = stringFromJNI();
final Button button = (Button)findViewById(R.id.dummy_button);
final String actualText = button.getText().toString();
if(message.equals(actualText)) {
button.setText("Dummy Button");
}
else {
button.setText(message);
}
return false;
}
};
Handler mHideHandler = new Handler();
Runnable mHideRunnable = new Runnable() {
@Override
public void run() {
mSystemUiHider.hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
}
17. Собираем и запускаем проект
Сначала Build->Make Project. На этом этапе собирается Java-часть.
Затем Run->Run ‘app’. А вот здесь, перед стартом приложения, будет происходить сборка C++ части. Если в ней будут какие-то ошибки, то об этом будет выведено сообщение. Если ошибок нет, то появится стандартный диалог выбора устройства, и, после нажатия OK приложение запустится.
Работа на реальном устройстве
Вывод сообщения в лог
Заключение
В целом, мне Android Studio понравилась. Интеграция Android SDK выполнена довольно плотно, иногда даже забываешь, что это запускаются отдельные программы. Есть всякие интересные плюшки, такие, как Help me choose. Понравилась новая система сборки — Gradle, — но тут же и недостаток: по ней очень мало информации.
Также, видно, что поддержка NDK еще сыровата, но прослеживается движение в этом направлении. Очень надеюсь, что они все-таки сделают полноценную поддержку C++-разработки.
P.S. Дебага C++ кода пока не обнаружено.
Source: Developer.android.com
Introduction
The Android Native Development Kit (NDK) allows developers to use C and C++ code with Android. It provides platform libraries for managing native activities and accessing physical device components like sensors and touch input. The NDK is particularly useful for squeezing extra performance out of a device, achieving low latency, or running computationally intensive applications like games or physics simulations. This guide walks you through installing and configuring the Android NDK on Windows, macOS, and Linux.
Prerequisites
Before starting, ensure you have the following:
- Android Studio: The recommended Integrated Development Environment (IDE) for Android development. Download the latest version from the official Android website.
- Java Development Kit (JDK): Required for the NDK to function. Use either the Oracle JDK or an open-source alternative like AdoptOpenJDK.
- Command Line Tools: Familiarity with command line tools is essential for managing the NDK and SDK.
Installing Android Studio
Download Android Studio
- Open your web browser and navigate to the official Android Studio download page.
- Click the «Download» button to get the Android Studio bundle.
Run the Installer
- Once the download completes, run the downloaded program.
- Follow the installation wizard to install all Android components.
Choose Installation Directories
- When prompted, choose installation directories for Android Studio and the Android SDK (e.g.,
C:\Android\android-studio
andC:\Android\sdk
).
Launch Android Studio
- After installation, launch Android Studio to ensure proper functionality.
- If prompted to import settings from a previous installation, select your preferred option and click «OK.»
Close the Welcome Screen
- Close the welcome screen as it will not be needed for now.
Installing the Android NDK
Download the NDK
- Navigate to the Android NDK download page.
- Select the NDK package for your development platform. The latest Long Term Support (LTS) version is recommended.
Extract the NDK Archive
- Once downloaded, extract the archive to a directory of your choice (e.g.,
C:\Android\ndk
).
Set Environment Variables
- Declare the Android SDK and NDK as environment variables to easily access Android utilities from the command line.
- Open the Environment Variables system window.
- Inside the System variables list, add:
ANDROID_SDK
variable with the SDK installation directory (e.g.,C:\Android\sdk
)ANDROID_NDK
variable with the NDK installation directory (e.g.,C:\Android\ndk
)
- Prepend
%ANDROID_SDK%\tools;%ANDROID_SDK%\platform-tools;%ANDROID_NDK%;
at the beginning of yourPATH
environment variable.
Verify NDK Installation
- Open a command prompt or terminal.
- List the Android devices connected to your computer using
adb devices
. - Check if the NDK is working by running
ndk-build -version
.
Configuring Android Studio for NDK
Open SDK Manager
- Open the Android SDK Manager, located in the ADB bundle directory’s root.
- Click «New» to select all the packages, then click «Install packages…»
- Accept the licenses in the popup and start the installation of Android development packages by clicking «Install.»
Install NDK and CMake
- With a project open, click Tools > SDK Manager.
- Click the SDK Tools tab.
- Select the NDK (Side by side) and CMake checkboxes.
- Click OK.
- A dialog box will show the space the NDK package consumes on disk. Click OK.
- When the installation completes, click Finish.
- Your project will automatically sync the build file and perform a build. Resolve any errors that occur.
Configuring Specific Versions of NDK
Install Specific Versions of NDK
- 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 corresponding to the NDK versions you want to install.
- Click OK.
- A dialog box will show the space the NDK package(s) consume. Click OK.
- When the installation completes, click Finish.
Configure Each Module with Specific Versions
- When using Android Studio 3.6 or higher, if you do not specify the version, the Android Gradle plugin chooses a compatible version.
- To configure each module with a specific version of the NDK, add the following to your module’s
build.gradle
file:
groovy
android {
…
externalNativeBuild {
cmake {
…
version «cmake-version»
}
}
}
Using CMake with NDK
Create or Import a Native Project
- Open Android Studio.
- Click on File > New > New Project.
- Select «Empty Activity» and click «Next.»
- Choose «C/C++» as the project type and click «Next.»
- Choose the NDK version you want to use and click «Finish.»
Add Native Source Files
- Open your project in Android Studio.
- Go to File > New > C/C++ Source File.
- Name your file (e.g.,
native-lib.cpp
) and click «OK.» - Add your native code in this file.
Configure CMake
-
Open your
build.gradle
file. -
Add the following configuration:
groovy
android {
…
externalNativeBuild {
cmake {
…
version «cmake-version»
}
}
} -
Ensure your
CMakeLists.txt
file is correctly configured to build your native library.
Debugging Native Code
Set Up LLDB
- The Native Development Kit (NDK) uses LLDB as its debugger.
- Ensure LLDB is installed and configured correctly.
Debugging Steps
- Open your project in Android Studio.
- Go to Run > Edit Configurations.
- Click the «+» button to create a new configuration.
- Choose «LLDB» as the debugger type and select your project.
- Set breakpoints in your native code and run the debugger.
Troubleshooting Common Issues
Environment Variables Not Set Correctly
- Ensure your environment variables are set correctly. If not, set them manually or use a script to automate the process.
NDK Not Recognized by Android Studio
- If the NDK is not recognized by Android Studio, try reinstalling it or checking if it is correctly installed in the specified directory.
CMake Configuration Issues
- If there are issues with CMake configuration, check if your
CMakeLists.txt
file is correctly configured and if all dependencies are included.
Gradle Build Errors
- If there are errors during the Gradle build process, check if all dependencies are correctly included in your
build.gradle
file and if there are any syntax errors.
Final Thoughts
Installing and configuring the Android NDK can seem complex at first, but following these steps will help you set up your development environment efficiently. Always check for updates and follow best practices to ensure smooth development and debugging of your native applications. The NDK is a powerful tool for achieving high performance and low latency in your applications, making it an essential part of any Android developer’s toolkit.
If you want to build and program Android apps, you must have the Android SDK installed on your computer. It’s also necessary for Windows users to be able to run code from an Android device. The SDK is available for download as a bundle or as a collection of command line tools. To install the SDK, you must first download and open the downloaded bundle. Then, open the Android SDK manager and select the Platforms, Tools, and Build Tools folders. You will also have to install the appropriate USB driver for Windows.
Depending on which version of Windows you are using, you may need to install a different SDK tool or platform. The NDK cannot be installed on older versions of Windows or Mac OS. For that, you need to install the Android SDK tools or Cygwin. Once you have done this, you should run ndk-build to compile the Java Android project. You will need to have an Android API level of 2.3 or higher to use the SDK.
Where is Android NDK Installed Windows 10?
Before installing the Android NDK, you must download the Android SDK. This version of the SDK is only compatible with the latest platform version. Before downloading the SDK, you must also make sure your computer meets the minimum system requirements. Once you have downloaded the NDK package, you can extract it with the 7z program. Then, follow the onscreen instructions to install it. You should now be able to use the Android NDK.
You can find the Android SDK installation location in the File Explorer. Open it and copy the location from the address bar. The location is C:UsersusernameAppDataLocalAndroidSdk. After that, you need to click “Open” and then select “Open with” and “adb devices” to start the installation process. Once the installation is complete, you can open Android Studio and begin programming!
The Android NDK is a companion tool to the Android SDK, which lets developers write native code for the most critical parts of their apps. Native code languages are very helpful when developing games, social apps, or other apps that require high performance. The NDK provides headers and libraries for C++, so you can use them to access hardware sensors, handle user input, and access application resources. It is important to note, however, that apps developed with this tool still run in a virtual machine on your device.
How Do I Download Android SDK And NDK?
To download the latest Android SDK and NDK on Windows, follow the steps below. First, you need to download android studio or eclipse. Once downloaded, they can be placed in the PATH environment variable to access the NDK packages. Once the installation is complete, you can run the software. Then, you can use it to develop Android apps. If you’re unsure of which version to download, you can use the SDK manager tool.
Once you have downloaded the SDK and NDK, you need to install them. Install them in a different location to save space. Make sure that you don’t leave any white spaces in the path, as this may cause problems with some of the tools. Once you’ve installed the Android SDK and NDK, open the SDK manager and click on the Tools tab. Once there, you’ll see a list of tools and platforms you need to install. Then, select any extra tools or packages you want to install.
The first thing to do is install Android SDK. To install NDK, you need to install the Android SDK first. If you don’t have the Android SDK installed, you can download it from a repository online. It contains sample Android applications. It is also recommended that you join the Android-ndk mailing list to receive updates on NDK development. You’ll need to install Android SDK to get the latest NDK version.
How Do I Install NDK 21?
In order to install Android NDK, you must be running a recent version of Cygwin and awk. Installing higher versions will not work with NDK tools. You can manually download the Android NDK or use the sdkmanager tool to install it. After downloading, you should save the installation files in a directory on your computer. Note that you may need to update the Java runtime if you wish to run the latest NDK versions.
To install Android NDK on Windows, you must download the corresponding package. Once downloaded, double-click the downloaded file and click “Install”. You can also use the command-line to manually extract the NDK packages. If you use a proxy, you can manually add the Android NDK link from a “Custom Update Site.”
Once the file is extracted, you can run the command ndk build to compile the project. If you’re using Android, be sure that the API level is at least 2.3. If you don’t, you will need to download the latest SDK version and GNU Make to run your Android application. When the project is complete, you can launch it using the ndk-build command.
Is NDK Necessary For Android Studio?
NDK is an external build tool for Android that supports native libraries. If your app is targeting a device running Android 2.2 or higher, you need to install the latest version of the SDK before you can install NDK. Likewise, you need to install a recent version of awk in order to compile your app. Moreover, you will need to select the appropriate NDK package depending on your CPU architecture.
While using NDK for Android does help with app development, it is not required for all applications. Using native code on Android increases app complexity and does not always result in noticeable performance improvements. Therefore, it is crucial to use NDK only when it is essential for the app and not because you prefer C. If you are unsure whether NDK is required, consult a certified Android developer first to see if it’s right for you.
If your app is for Android 2.3 or higher, you can use the NDK to compile native activities. However, this does require the use of Cygwin, an open source collection of software that enables the Windows platform to emulate the Unix environment. It is a layer between Windows OS and POSIX software, and it is required by the Android NDK compile system.
How Do I Know If Android Ndk is Installed?
To find out whether the Android NDK is installed on your PC, follow these steps. In your current working directory, search for a folder named android-ndk-rXXX. This folder contains all the NDK files. If you don’t see this folder, then you may have to install it manually. If you are using a command-line compiler, you might need to change the environment variables.
The Android SDK is installed in the /Library/Android/sdk directory on your PC. If you need to install additional tools, you can choose a different location by using the SDK Manager. The SDK Manager allows you to choose which folders to install from. The Tools tab lists the extra tools and programs, including an Android emulator, a low-level debugger, and the Google Play libraries. You can click on the download or installation progress bar to see which tools are installed.
NDK is a toolkit that enables developers to write native Android applications. You can download it from the SDK tools directory. You can then add it to your PATH variable. To install the NDK, you can also add the NDK to your computer’s path. You can then access the NDK using your IDE, such as Visual Studio. If you don’t see the SDK installer, click on the download button.
Where Does Visual Studio Install Ndk?
Where Does Visual Studio Install Android Ndk? The Android Game Development Extension is an extension that will install the Android Native Development Kit on your Windows machine. This extension will allow you to run a sample Visual Studio C++ project on an actual Android device or emulator. You can download the Android Game Development Extension from the Downloads page. You will need to run the installation procedure, which can take several minutes. Next, select the Android NDK in the extension toolbar.
If you’re using vs2010 or vs2012, the installer will be separate. Make sure to check that the version of your toolchain is compatible with the version of Android you are using. If you’re using vs2012, you’ll have to install Visual Studio 2012, but if you’re using an express version, it’s likely to work just fine. Also, note that NDK r9c is the minimum requirement for NDKs. The new NDK comes with the toolchain 4.8.
First, you will need to download the Android SDK tools for your Windows PC. They will be placed in a folder called “Android” on your computer’s hard drive. After downloading the SDK, you will need to extract them. To do this, you can use the command line to extract them. You will also need Java installed on your computer. This is a free download available from Oracle’s website.
To install Android SDK tools, you must first install Android Studio and an emulator called Android Virtual Device. Launch the application and wait for the download to complete. After it finishes, add the Android SDK Tools directory to your PATH. The Android SDK manager is in this directory. Once you’ve installed the SDK tools, you can use Android Studio to build Android apps. The tools also work with Ionic.
The Android SDK tools are essential for creating apps. These tools include the Android Debug Bridge. These tools let you install and run Android applications and access additional shell tools. To get started, follow the instructions below. Just follow the steps in the instructions carefully. You should be able to develop Android apps quickly and easily. If you’re unsure of how to install these tools on Windows, check out the Android Central podcast!
Learn More Here:
1.) Android Help Center
2.) Android – Wikipedia
3.) Android Versions
4.) Android Guides
Introduction
Since most of the NDK tools are coming from the Linux environment, that OS was my first approach in building native C applications for Android. See this tutorial for a start.
However, I also needed to be able to compile JNI Android apps using the Windows environment. It proved an easy task, but there were some issues, so I decided to write this guide.
Install Android NDK on Windows and use it to compile a JAVA/JNI application
You will need an internet connection to install Cygwin and the Android SDK automatically from the Internet.
Download link.
Current version of the file is: android-ndk-r4b-windows.zip 45MB
Download link. (Direct Link)
Select the mirror you need to download from then follow the installation guide.
On package selection, Open Devel category and check “make”:
I’ve installed it to C:\cygwin
Download link.
Current version is android-sdk_r06-windows.zip 23MB
4.1) Unzip the zip content to a location on your harddisk. I choose:
D:\work_code\android\android-sdk-windows\
You will find SDK Setup.exe . Run it. I get a warning to install JAVA JDK
4.2) Download Java JDK
Download link.
Select platform “Windows”. Current file is: jdk-6u21-windows-i586.exe (Direct link)
4.3) Install the Java JDK: simply run the exe . It takes a few minutes to complete.
4.4) Re-run the SDK Setup.exe from the Android SDK.
This opens the Android SDK and AVD Manager. If you get a HTTPS Error:
go to Settings and check the “Force https:// …” checkbox:
4.5) Go to Available Packages, select all, and press Install Selected:
The installer will download the packages from the internet, and might prompt you to accept terms, which you must do if you want to continue with the installation. This step takes a few minutes.
5.1) Unzip the NDK zip file. My choice is: D:\work_code\android\android-ndk-r4b\
5.2) Configure Cygwin parameters
Go to the Cygwin folder and open Cygwin.bat. It contains something like this:
@echo off C: chdir C:\cygwin\bin bash --login -i
Using any text editor change it to:
@echo off set IS_UNIX= set DEV_ROOT=d:/work_code/android/BlueInput set JAVA_HOME=c:/Progra~1/Java/jdk1.6.0_21 set CLASSPATH=d:/work_code/android/BlueInput/obj set PATH=D:/work_code/android/android-sdk-windows/tools;D:/work_code/android/android-ndk-r4b set ANDROID_NDK_ROOT=/cygdrive/d/work_code/android-ndk-r4b set NDK_PROJECT_PATH=/cygdrive/d/work_code/android/BlueInput C: chdir C:\cygwin\bin bash --login -i
The path in the config, d:/work_code/android/BlueInput, is something I’m currently working on. Change to your Own project name. The project must be organized as follows:
A) The JNI part (the .c and .h and Android.mk files) in:
d:/work_code/android/BlueInput/jni
B) The JAVA part (assets,bin,gen,jni,libs,obj,res,src with the .java files) in:
d:/work_code/android/BlueInput
For these paths always use forward slashes.
5.3) Open Cygwin and browse to the NDK folder, using cd [enter] :
cd d:/work_code/android-ndk-r4b
5.4) Type ./ndk-build to compile the JNI project
The C files have been successfully built. Now using Eclipse, you can build the Java android project, and it will include the JNI part automatically. Easy.
1. Install Python, CMake, Ninja, Git, and JDK 8¶
-
Download and install Python3 from https://www.python.org/downloads/ (ca. 25MB).
Important: Make sure to activate the “Add Python to PATH» checkbox at the bottom of the installer window.
-
Download and install CMake from https://cmake.org/download/ (ca. 19MB). We recommend using the latest win64-x64 stable release installer binary.
Important: When installing CMake, make sure to choose “Add the Cmake binary to the PATH environment variable”.
-
Download and install Ninja from https://github.com/ninja-build/ninja/releases. We recommend using the latest Ninja version.
-
Download and install git from https://git-scm.com/download/win (ca. 42MB). If you’re unsure about the available options presented in the installer, just keep the default settings.
-
Dowload and install JDK 8 from https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html (ca. 200MB).
2. Install Android Studio¶
2.1 Download and Install Android Studio¶
- Download Android Studio from https://developer.android.com/studio/ (ca. 1GB) and start the downloaded EXE file.
- Follow the steps in the setup wizard.
- Stay on the «Welcome to Android» screen and complete the steps below to complete the installation.
Note
It’s sufficient to select the default setup type in the Android Studio Setup wizard. When asked, grant permission to the Intel HAXM installer to enable Android device emulation.
2.2 Install Android NDK¶
- On the “Welcome to Android” screen, click Configure and select SDK Manager.
- Click on the SDK Tools tab.
- Select NDK from the list and click OK.
- Confirm the change by clicking OK in the popup window.
- Accept the NDK license agreement.
- The NDK component is being installed, grab another drink.
- After the installation has finished, click Finish. The installation is now complete.
Didn’t work?¶
Please let us know. We’re happy to help!