SlideShare a Scribd company logo
1 of 44
Download to read offline
MasteringtheNDKwith Android Studio 2.0+ and the gradle-experimental plugin
Xavier Hallade
Application Engineer @ Intel
#droidconIT
Mastering the NDK - Agenda
The Android NDK
Brief history of Android Studio support of the NDK
What we can do now with Android Studio
Migrating to the gradle-experimental plugin
Configuring your projects
Q&A
TheAndroidNDK
Let’s briefly reexamine what it is and how it works
#droidconIT
The Android NDK
Checking .so files
https://play.google.com/store/apps/details?id=co
m.xh.nativelibsmonitor.app
#droidconIT
Java Native Interface (JNI)
Java side
 System.loadLibrary()
 native keyword
C/C++ side - .so files
 #include <jni.h>
– Java primitive types, objects, methods
– JNIEnv*, JavaVM*
#droidconIT
use and return Java primitives and objects
jint xxx(JNIEnv* env, jclass cls, …)
use a specific function name:
Java_com_example_hellojni_MainActivity_method
or do a manual registration using
JNIEnv->RegisterNatives()
Mapping C/C++ implementations to Java methods
Uses Android.mk and Application.mk Makefiles.
The NDK will generate optimized code for all target ABIs
You can also pass APP_ABI variable to ndk-build, and specify each ABI:
ndk-build APP_ABI=x86
all32 and all64 are also possible values.
ndk-build(.cmd) – the historical tool
Build ARM64 libs
Build x86_64 libs
Build mips64 libs
Build ARMv7a libs
Build ARMv5 libs
Build x86 libs
Build mips libs
#droidconIT
Classic* execution flow
1. .so files loaded in memory by System.loadLibrary()
1. C/C++ functions  Java native methods
2. DVM/ART encounters a call to a native method
1. its C/C++ implementation is executed
2. then, Java code execution goes on
* android.app.NativeActivity/ native_activity.h allow
to develop without having Java code inside the app.
AndroidStudioandtheNDK
Where are we now?
#droidconIT
Android Studio and the NDK – a brief history
• December 2013: gradle 0.7.3 – “sort of” support for the NDK
• December 2014: Eclipse ADT no longer in development
• May 2015: Integration of CLion announced at Google I/O
• July 2015: first availability, with a lot of limitations
• Since April 7th (yesterday night!): first stable version of the experimental
plugin available, and everything is awesome !!
ASNDKCodeediting
Demo
13
ASNDKDebugging
Demo
HowtogetThis?
#droidconIT
Solutions to use the NDK with gradle/AS
• gradle(-stable) plugin, deprecated Android NDK support
• gradle(-stable) plugin, manual call to NDK build
• gradle(-experimental) plugin, experimental but stable since yesterday
• mixing gradle-stable and –experimental plugins
#droidconIT
gradle(-stable) plugin, deprecated Android NDK support
- bad APP_PLATFORM handling
- it’s deprecated!
#droidconIT
gradle(-stable) plugin, manual call to NDK build
+ stable
+ most configurable solution (using Android.mk/Application.mk)
+ supports generating split APKs with proper version codes
~ C/C++ code editing inside Android Studio
- No C/C++ code debugging inside Android Studio
#droidconIT
gradle(-experimental) plugin, built-in NDK support
+ full code editing/debugging within Android Studio
+ good support for native dependencies since 0.6.0-alpha1
- it’s experimental and the documentation barely exists yet
- can’t generate split APKs with proper version codes
- Many incompatible plugins.
#droidconIT
Mixing gradle-stable and gradle-experimental plugins
+ full code editing/debugging support within Android Studio
+ good support for native dependencies since 0.6.0
+ can generate split APKs with proper version codes
+ all the plugins are supported
- it’s experimental and the documentation barely exists yet
#droidconIT
Using the right versions
Android Studio 1.5 2.0 2.1-preview5
gradle 2.8 2.10 2.10
gradle plugin 1.5.0 2.0.0 2.1.0-alpha5
gradle-experimental plugin 0.4.0 0.6.0 0.7.0-alpha5
Migratingtogradle-experimental
#droidconIT
Gradle experimental plugin
dependencies {
classpath 'com.android.tools.build:gradle-experimental:0.6.0'
}
com.android.model. application / library / native
model{}
.with{}
distributionUrl=https://services.gradle.org/distributions/gradle-2.10-all.zip
.add() / .addAll() / .removeAll()
#droidconIT
Example of build.gradle update to gradle-experimental
apply plugin: 'com.android.application'
android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
defaultConfig {
applicationId "com.ph0b.example"
minSdkVersion 15
targetSdkVersion 23
versionCode 4
versionName "1.0.1"
ndk {
moduleName "mymodule"
ldLibs "log"
stl "gnustl_static"
cFlags "-std=c++11 -fexceptions"
}
}
signingConfigs {
release {
storeFile file(STORE_FILE)
storePassword STORE_PASSWORD
keyAlias KEY_ALIAS
keyPassword KEY_PASSWORD
}
}
buildTypes {
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.txt'
signingConfig signingConfigs.release
}
debug {
jniDebuggable true
}
}
}
apply plugin: 'com.android.model.application'
model {
android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
defaultConfig.with {
applicationId "com.ph0b.example"
minSdkVersion.apiLevel 15
targetSdkVersion.apiLevel 23
versionCode 4
versionName "1.0.1"
}
}
android.ndk {
moduleName = "mymodule"
ldLibs.addAll(['log'])
cppFlags.add("-std=c++11“)
cppFlags.add("-fexceptions“)
stl = 'gnustl_static'
}
android.signingConfigs {
create("release") {
keyAlias KEY_ALIAS
keyPassword STORE_PASSWORD
storeFile file(STORE_FILE)
storePassword KEY_PASSWORD
}
}
android.buildTypes {
release {
signingConfig = $("android.signingConfigs.release“)
minifyEnabled true
proguardFiles.add(file('proguard-rules.txt'))
}
}
}
#droidconIT
NDK configurability
android.ndk {
moduleName
platformVersion
toolchain
toolchainVersion
cFlags
cppFlags
ldLibs
ldFlags
abiFilters
stl
renderscriptNdkMode
debuggable
}
android.abis { // 0.7.0+
create("ABI") { //ABI can be any of x86, x86_64,
armeabi-v7a, arm64-v8a…
cppFlags
ldLibs
ldFlags
}
}
#droidconIT
Android Studio configuration
Gradleconfigurationexamples
#droidconIT
android.ndk {
moduleName = "TeapotNativeActivity"
platformVersion = 17
cppFlags.add("-I${file("src/main/jni/native_app_glue")}".toString())
cppFlags.add("-I${file("src/main/jni/cpufeatures")}".toString())
cppFlags.add("-I${file("src/main/jni/ndk_helper")}".toString())
ldLibs.addAll(["android", "EGL", "GLESv2", "dl", "log"])
stl = "stlport_static"
}
build.gradle
Native dependencies (with sources)
#droidconIT
android.sources {
main{
jni {
source {
srcDir 'src/main/XXX'//folder
srcDir 'src/main/YYY'//other folder
exclude "**/not_this_one.c" //single file
}
}
}
}
build.gradle
Adding/Removing native sources to be compiled
repositories { libs(PrebuiltLibraries) { myexternallib {
headers.srcDir "src/main/jni/prebuilts/include"
binaries.withType(SharedLibraryBinary) {
sharedLibraryFile =
file("src/main/jni/prebuilts/${targetPlatform.getName()}/libmyexternallib.so")
}
}}}
android.ndk {
moduleName = "TeapotNativeActivity"
platformVersion = 17
ldLibs.addAll(["android", "EGL", "GLESv2", "dl", "log"])
stl = "stlport_static"
}
android.sources { main { jni { dependencies {
library "myexternallib" linkage "dynamic" //dynamic is default / can be static too
}}}}
build.gradle
Native dependencies (prebuilts)
apply plugin: 'com.android.model.application'
model {
def versionCodeBase = 11;
def versionCodePrefixes = ['armeabi': 1, 'armeabi-v7a': 2, 'arm64-v8a': 3, 'mips': 5,
'mips64': 6, 'x86': 8, 'x86_64': 9];
//...
android.productFlavors {
create ("armv7") {
ndk.abiFilters.add("armeabi-v7a")
versionCode = versionCodePrefixes.get("armeabi-v7a", 0) * 1000000 + versionCodeBase
}
create ("x86") {
ndk.abiFilters.add("x86")
versionCode = versionCodePrefixes.get("x86", 0) * 1000000 + versionCodeBase
}
}
}
build.gradle
Multiple APKs (gradle-experimental)
//project’s build.gradle:
buildscript {
…
dependencies {
classpath 'com.android.tools.build:gradle-experimental:0.6.0'
classpath 'com.android.tools.build:gradle:2.0.0'
}
}
//to keep debugging working, set this in the build.gradle that uses the stable plugin:
android{
buildTypes.debug.jniDebuggable true
}
/! use the latest versions for both plugins, don’t mix older ones.
build.gradle
Mixing gradle stable and -experimental plugins
Mixing gradle stable and -experimental plugins
…and keep debugging working in AS:
#droidconIT
splits {
abi {
enable true
reset()
include 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a'
universalApk true
}
}
// map for the version code
project.ext.versionCodes = ['armeabi': 1, 'armeabi-v7a': 2, 'arm64-v8a': 3,
'mips': 5, 'mips64': 6, 'x86': 8, 'x86_64': 9]
applicationVariants.all { variant ->
// assign different version code for each output
variant.outputs.each { output ->
output.versionCodeOverride =
project.ext.versionCodes.get(output.getFilter(com.android.build.OutputFile.ABI),
0) * 1000000 + defaultConfig.versionCode
}
}
build.gradle
Multiple APKs (APK Splits – gradle-stable)
Q&A@ph0b – ph0b.com – +XavierHallade
#droidconIT
Resources
http://ph0b.com/new-android-studio-ndk-support/
https://github.com/googlesamples/android-ndk
Watch for this issue to be resolved for fixing editing on Windows versions of AS:
http://b.android.com/195483
Additionalslides
Multiple APKs and version codes handling
Google Play* supports multiple APKs for the same application.
What compatible APK will be chosen for a device entirely depends on the
android:versionCode
If you have multiple APKs for multiple ABIs, best is to simply prefix your current
version code with a digit representing the ABI:
2310 3310 6310 7310
You can have more options for multiple APKs, here is a convention that will work if
you’re using all of these:
x86ARMv7 ARM64 X86_64
#droidconIT
Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := hello-jni
LOCAL_SRC_FILES := hello-jni.c
include $(BUILD_SHARED_LIBRARY)
Other useful variables:
LOCAL_C_INCLUDES := ./headers/
LOCAL_EXPORT_C_INCLUDES := ./headers/
LOCAL_SHARED_LIBRARIES := module_shared
LOCAL_STATIC_LIBRARIES := module_static
Other predefined macros:
BUILD_SHARED_LIBRARY, BUILD_STATIC_LIBRARY,
PREBUILT_SHARED_LIBRARY, PREBUILT_STATIC_LIBRARY
#droidconIT 43
Application.mk
APP_PLATFORM := android-15 # <= minSDKVersion
APP_CFLAGS := -O3
APP_STL := c++_shared
APP_ABI := all # or all32, all64…
APP_OPTIM := release # default
NDK_TOOCLHAIN_VERSION := 4.8 # default
import org.apache.tools.ant.taskdefs.condition.Os
android.sources {
main {
jni {
source {
srcDirs = ['src/main/none']
}
}
jniLibs {
source {
srcDirs = ['src/main/libs']
}
}
}
}
task ndkBuild(type: Exec) {
def ndkBuildExt = Os.isFamily(Os.FAMILY_WINDOWS) ? ".cmd" : ""
commandLine "ndk-build${ndkBuildExt}", '-C', file('src/main').absolutePath
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn ndkBuild
}
build.gradle
Using Android.mk/Application.mk from Gradle

More Related Content

What's hot

Is Android the New Embedded Linux? at AnDevCon VI
Is Android the New Embedded Linux? at AnDevCon VIIs Android the New Embedded Linux? at AnDevCon VI
Is Android the New Embedded Linux? at AnDevCon VI
Opersys inc.
 
android_project
android_projectandroid_project
android_project
Adit Ghosh
 
DEVIEW2013: Automating Performance Tests for Android Applications
DEVIEW2013: Automating Performance Tests for Android ApplicationsDEVIEW2013: Automating Performance Tests for Android Applications
DEVIEW2013: Automating Performance Tests for Android Applications
Kyungmin Lee
 
Applico Android Info Session at Columbia University
Applico Android Info Session at Columbia UniversityApplico Android Info Session at Columbia University
Applico Android Info Session at Columbia University
Applico
 
OWF12/PAUG Conf Days Alternative to google's android emulator, daniel fages, ...
OWF12/PAUG Conf Days Alternative to google's android emulator, daniel fages, ...OWF12/PAUG Conf Days Alternative to google's android emulator, daniel fages, ...
OWF12/PAUG Conf Days Alternative to google's android emulator, daniel fages, ...
Paris Open Source Summit
 
UIViewControllerのコーナーケース
UIViewControllerのコーナーケースUIViewControllerのコーナーケース
UIViewControllerのコーナーケース
Katsumi Kishikawa
 

What's hot (20)

Getting started with android dev and test perspective
Getting started with android   dev and test perspectiveGetting started with android   dev and test perspective
Getting started with android dev and test perspective
 
Android, Gradle & Dependecies
Android, Gradle & DependeciesAndroid, Gradle & Dependecies
Android, Gradle & Dependecies
 
Is Android the New Embedded Linux? at AnDevCon VI
Is Android the New Embedded Linux? at AnDevCon VIIs Android the New Embedded Linux? at AnDevCon VI
Is Android the New Embedded Linux? at AnDevCon VI
 
Google App Engine for Java v0.0.2
Google App Engine for Java v0.0.2Google App Engine for Java v0.0.2
Google App Engine for Java v0.0.2
 
Android Things - The IoT platform from Google
Android Things - The IoT platform from GoogleAndroid Things - The IoT platform from Google
Android Things - The IoT platform from Google
 
android_project
android_projectandroid_project
android_project
 
Android 10 Internals Update
Android 10 Internals UpdateAndroid 10 Internals Update
Android 10 Internals Update
 
Optimizing apps for better performance extended
Optimizing apps for better performance extended Optimizing apps for better performance extended
Optimizing apps for better performance extended
 
Apache Maven - eXo VN office presentation
Apache Maven - eXo VN office presentationApache Maven - eXo VN office presentation
Apache Maven - eXo VN office presentation
 
Introduction to android coding
Introduction to android codingIntroduction to android coding
Introduction to android coding
 
Android Development Tutorial V3
Android Development Tutorial   V3Android Development Tutorial   V3
Android Development Tutorial V3
 
DEVIEW2013: Automating Performance Tests for Android Applications
DEVIEW2013: Automating Performance Tests for Android ApplicationsDEVIEW2013: Automating Performance Tests for Android Applications
DEVIEW2013: Automating Performance Tests for Android Applications
 
[Android Codefest Germany] Adding x86 target to your Android app by Xavier Ha...
[Android Codefest Germany] Adding x86 target to your Android app by Xavier Ha...[Android Codefest Germany] Adding x86 target to your Android app by Xavier Ha...
[Android Codefest Germany] Adding x86 target to your Android app by Xavier Ha...
 
Applico Android Info Session at Columbia University
Applico Android Info Session at Columbia UniversityApplico Android Info Session at Columbia University
Applico Android Info Session at Columbia University
 
Android Things - The IoT platform for everyone.
Android Things - The IoT platform for everyone. Android Things - The IoT platform for everyone.
Android Things - The IoT platform for everyone.
 
Getting your app on Android TV
Getting your app on Android TVGetting your app on Android TV
Getting your app on Android TV
 
[Ultracode Munich Meetup #7] Building Apps for Nexus Player & Android TV
[Ultracode Munich Meetup #7] Building Apps for Nexus Player & Android TV[Ultracode Munich Meetup #7] Building Apps for Nexus Player & Android TV
[Ultracode Munich Meetup #7] Building Apps for Nexus Player & Android TV
 
OWF12/PAUG Conf Days Alternative to google's android emulator, daniel fages, ...
OWF12/PAUG Conf Days Alternative to google's android emulator, daniel fages, ...OWF12/PAUG Conf Days Alternative to google's android emulator, daniel fages, ...
OWF12/PAUG Conf Days Alternative to google's android emulator, daniel fages, ...
 
Android Things
Android ThingsAndroid Things
Android Things
 
UIViewControllerのコーナーケース
UIViewControllerのコーナーケースUIViewControllerのコーナーケース
UIViewControllerのコーナーケース
 

Viewers also liked

Android - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTaskAndroid - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTask
Hoang Ngo
 
Using the Presentation API and external screens on Android
Using the Presentation API and external screens on AndroidUsing the Presentation API and external screens on Android
Using the Presentation API and external screens on Android
Xavier Hallade
 
Overview of Android binder IPC implementation
Overview of Android binder IPC implementationOverview of Android binder IPC implementation
Overview of Android binder IPC implementation
Chethan Pchethan
 

Viewers also liked (20)

Efficient Android Threading
Efficient Android ThreadingEfficient Android Threading
Efficient Android Threading
 
Android - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTaskAndroid - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTask
 
World-Class Testing Development Pipeline for Android
 World-Class Testing Development Pipeline for Android World-Class Testing Development Pipeline for Android
World-Class Testing Development Pipeline for Android
 
PublishSubject
PublishSubjectPublishSubject
PublishSubject
 
A realtime infrastructure for Android apps: Firebase may be what you need..an...
A realtime infrastructure for Android apps: Firebase may be what you need..an...A realtime infrastructure for Android apps: Firebase may be what you need..an...
A realtime infrastructure for Android apps: Firebase may be what you need..an...
 
Add ClassyShark to your Android toolbox
Add ClassyShark to your Android toolboxAdd ClassyShark to your Android toolbox
Add ClassyShark to your Android toolbox
 
Data Binding in Action using MVVM pattern
Data Binding in Action using MVVM patternData Binding in Action using MVVM pattern
Data Binding in Action using MVVM pattern
 
Building maintainable app
Building maintainable appBuilding maintainable app
Building maintainable app
 
Android Multimedia Framework
Android Multimedia FrameworkAndroid Multimedia Framework
Android Multimedia Framework
 
Using the Presentation API and external screens on Android
Using the Presentation API and external screens on AndroidUsing the Presentation API and external screens on Android
Using the Presentation API and external screens on Android
 
Overview of Android binder IPC implementation
Overview of Android binder IPC implementationOverview of Android binder IPC implementation
Overview of Android binder IPC implementation
 
Dalvik Source Code Reading
Dalvik Source Code ReadingDalvik Source Code Reading
Dalvik Source Code Reading
 
Contextual communications and why you should care - Droidcon DE
Contextual communications and why you should care - Droidcon DEContextual communications and why you should care - Droidcon DE
Contextual communications and why you should care - Droidcon DE
 
Android session 2-behestee
Android session 2-behesteeAndroid session 2-behestee
Android session 2-behestee
 
Form Handling using PHP
Form Handling using PHPForm Handling using PHP
Form Handling using PHP
 
Tomasz Polanski - Automated mobile testing 2016 - Testing: why, when, how
Tomasz Polanski - Automated mobile testing 2016 - Testing: why, when, howTomasz Polanski - Automated mobile testing 2016 - Testing: why, when, how
Tomasz Polanski - Automated mobile testing 2016 - Testing: why, when, how
 
Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
 
10 ways to improve your Android app performance
10 ways to improve your Android app performance10 ways to improve your Android app performance
10 ways to improve your Android app performance
 
Android async task
Android async taskAndroid async task
Android async task
 
Unit testing without Robolectric, Droidcon Berlin 2016
Unit testing without Robolectric, Droidcon Berlin 2016Unit testing without Robolectric, Droidcon Berlin 2016
Unit testing without Robolectric, Droidcon Berlin 2016
 

Similar to Mastering the NDK with Android Studio 2.0 and the gradle-experimental plugin

Similar to Mastering the NDK with Android Studio 2.0 and the gradle-experimental plugin (20)

Gradle presentation
Gradle presentationGradle presentation
Gradle presentation
 
Hello, Android Studio 3.2 & Android App Bundle @ I/O Extended Bangkok 2018
Hello, Android Studio 3.2 & Android App Bundle @ I/O Extended Bangkok 2018Hello, Android Studio 3.2 & Android App Bundle @ I/O Extended Bangkok 2018
Hello, Android Studio 3.2 & Android App Bundle @ I/O Extended Bangkok 2018
 
Getting started with building your own standalone Gradle plugin
Getting started with building your own standalone Gradle pluginGetting started with building your own standalone Gradle plugin
Getting started with building your own standalone Gradle plugin
 
Android gradle-build-system-overview
Android gradle-build-system-overviewAndroid gradle-build-system-overview
Android gradle-build-system-overview
 
Enter the gradle
Enter the gradleEnter the gradle
Enter the gradle
 
Hacking the Codename One Source Code - Part IV - Transcript.pdf
Hacking the Codename One Source Code - Part IV - Transcript.pdfHacking the Codename One Source Code - Part IV - Transcript.pdf
Hacking the Codename One Source Code - Part IV - Transcript.pdf
 
Comment développer une application mobile en 8 semaines - Meetup PAUG 24-01-2023
Comment développer une application mobile en 8 semaines - Meetup PAUG 24-01-2023Comment développer une application mobile en 8 semaines - Meetup PAUG 24-01-2023
Comment développer une application mobile en 8 semaines - Meetup PAUG 24-01-2023
 
Getting started with the NDK
Getting started with the NDKGetting started with the NDK
Getting started with the NDK
 
Mobile development in 2020
Mobile development in 2020 Mobile development in 2020
Mobile development in 2020
 
Hands on the Gradle
Hands on the GradleHands on the Gradle
Hands on the Gradle
 
Moderne Android Builds mit Gradle
Moderne Android Builds mit GradleModerne Android Builds mit Gradle
Moderne Android Builds mit Gradle
 
#BABBQAmsterdam The other Android getting started guide: Gradle power
#BABBQAmsterdam The other Android getting started guide: Gradle power#BABBQAmsterdam The other Android getting started guide: Gradle power
#BABBQAmsterdam The other Android getting started guide: Gradle power
 
Level Up Your Android Build -Droidcon Berlin 2015
Level Up Your Android Build -Droidcon Berlin 2015Level Up Your Android Build -Droidcon Berlin 2015
Level Up Your Android Build -Droidcon Berlin 2015
 
[DEPRECATED]Gradle the android
[DEPRECATED]Gradle the android[DEPRECATED]Gradle the android
[DEPRECATED]Gradle the android
 
Gitlab ci e kubernetes, build test and deploy your projects like a pro
Gitlab ci e kubernetes, build test and deploy your projects like a proGitlab ci e kubernetes, build test and deploy your projects like a pro
Gitlab ci e kubernetes, build test and deploy your projects like a pro
 
What's new in Gradle 4.0
What's new in Gradle 4.0What's new in Gradle 4.0
What's new in Gradle 4.0
 
Gradle,the new build system for android
Gradle,the new build system for androidGradle,the new build system for android
Gradle,the new build system for android
 
Android Studio vs. ADT
Android Studio vs. ADTAndroid Studio vs. ADT
Android Studio vs. ADT
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
Module-I_Introduction-to-Android.pptx
Module-I_Introduction-to-Android.pptxModule-I_Introduction-to-Android.pptx
Module-I_Introduction-to-Android.pptx
 

Recently uploaded

TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc
 
CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)
Wonjun Hwang
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
panagenda
 

Recently uploaded (20)

Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
How to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfHow to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cf
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - Questionnaire
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
How to Check GPS Location with a Live Tracker in Pakistan
How to Check GPS Location with a Live Tracker in PakistanHow to Check GPS Location with a Live Tracker in Pakistan
How to Check GPS Location with a Live Tracker in Pakistan
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development Companies
 
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps Productivity
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdf
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overview
 
CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
 

Mastering the NDK with Android Studio 2.0 and the gradle-experimental plugin

  • 1. MasteringtheNDKwith Android Studio 2.0+ and the gradle-experimental plugin Xavier Hallade Application Engineer @ Intel
  • 2. #droidconIT Mastering the NDK - Agenda The Android NDK Brief history of Android Studio support of the NDK What we can do now with Android Studio Migrating to the gradle-experimental plugin Configuring your projects Q&A
  • 3. TheAndroidNDK Let’s briefly reexamine what it is and how it works
  • 6. #droidconIT Java Native Interface (JNI) Java side  System.loadLibrary()  native keyword C/C++ side - .so files  #include <jni.h> – Java primitive types, objects, methods – JNIEnv*, JavaVM*
  • 7. #droidconIT use and return Java primitives and objects jint xxx(JNIEnv* env, jclass cls, …) use a specific function name: Java_com_example_hellojni_MainActivity_method or do a manual registration using JNIEnv->RegisterNatives() Mapping C/C++ implementations to Java methods
  • 8. Uses Android.mk and Application.mk Makefiles. The NDK will generate optimized code for all target ABIs You can also pass APP_ABI variable to ndk-build, and specify each ABI: ndk-build APP_ABI=x86 all32 and all64 are also possible values. ndk-build(.cmd) – the historical tool Build ARM64 libs Build x86_64 libs Build mips64 libs Build ARMv7a libs Build ARMv5 libs Build x86 libs Build mips libs
  • 9. #droidconIT Classic* execution flow 1. .so files loaded in memory by System.loadLibrary() 1. C/C++ functions  Java native methods 2. DVM/ART encounters a call to a native method 1. its C/C++ implementation is executed 2. then, Java code execution goes on * android.app.NativeActivity/ native_activity.h allow to develop without having Java code inside the app.
  • 11. #droidconIT Android Studio and the NDK – a brief history • December 2013: gradle 0.7.3 – “sort of” support for the NDK • December 2014: Eclipse ADT no longer in development • May 2015: Integration of CLion announced at Google I/O • July 2015: first availability, with a lot of limitations • Since April 7th (yesterday night!): first stable version of the experimental plugin available, and everything is awesome !!
  • 13. 13
  • 14.
  • 16.
  • 18. #droidconIT Solutions to use the NDK with gradle/AS • gradle(-stable) plugin, deprecated Android NDK support • gradle(-stable) plugin, manual call to NDK build • gradle(-experimental) plugin, experimental but stable since yesterday • mixing gradle-stable and –experimental plugins
  • 19. #droidconIT gradle(-stable) plugin, deprecated Android NDK support - bad APP_PLATFORM handling - it’s deprecated!
  • 20. #droidconIT gradle(-stable) plugin, manual call to NDK build + stable + most configurable solution (using Android.mk/Application.mk) + supports generating split APKs with proper version codes ~ C/C++ code editing inside Android Studio - No C/C++ code debugging inside Android Studio
  • 21. #droidconIT gradle(-experimental) plugin, built-in NDK support + full code editing/debugging within Android Studio + good support for native dependencies since 0.6.0-alpha1 - it’s experimental and the documentation barely exists yet - can’t generate split APKs with proper version codes - Many incompatible plugins.
  • 22. #droidconIT Mixing gradle-stable and gradle-experimental plugins + full code editing/debugging support within Android Studio + good support for native dependencies since 0.6.0 + can generate split APKs with proper version codes + all the plugins are supported - it’s experimental and the documentation barely exists yet
  • 23. #droidconIT Using the right versions Android Studio 1.5 2.0 2.1-preview5 gradle 2.8 2.10 2.10 gradle plugin 1.5.0 2.0.0 2.1.0-alpha5 gradle-experimental plugin 0.4.0 0.6.0 0.7.0-alpha5
  • 25. #droidconIT Gradle experimental plugin dependencies { classpath 'com.android.tools.build:gradle-experimental:0.6.0' } com.android.model. application / library / native model{} .with{} distributionUrl=https://services.gradle.org/distributions/gradle-2.10-all.zip .add() / .addAll() / .removeAll()
  • 26. #droidconIT Example of build.gradle update to gradle-experimental apply plugin: 'com.android.application' android { compileSdkVersion rootProject.ext.compileSdkVersion buildToolsVersion rootProject.ext.buildToolsVersion defaultConfig { applicationId "com.ph0b.example" minSdkVersion 15 targetSdkVersion 23 versionCode 4 versionName "1.0.1" ndk { moduleName "mymodule" ldLibs "log" stl "gnustl_static" cFlags "-std=c++11 -fexceptions" } } signingConfigs { release { storeFile file(STORE_FILE) storePassword STORE_PASSWORD keyAlias KEY_ALIAS keyPassword KEY_PASSWORD } } buildTypes { release { minifyEnabled true shrinkResources true proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.txt' signingConfig signingConfigs.release } debug { jniDebuggable true } } } apply plugin: 'com.android.model.application' model { android { compileSdkVersion rootProject.ext.compileSdkVersion buildToolsVersion rootProject.ext.buildToolsVersion defaultConfig.with { applicationId "com.ph0b.example" minSdkVersion.apiLevel 15 targetSdkVersion.apiLevel 23 versionCode 4 versionName "1.0.1" } } android.ndk { moduleName = "mymodule" ldLibs.addAll(['log']) cppFlags.add("-std=c++11“) cppFlags.add("-fexceptions“) stl = 'gnustl_static' } android.signingConfigs { create("release") { keyAlias KEY_ALIAS keyPassword STORE_PASSWORD storeFile file(STORE_FILE) storePassword KEY_PASSWORD } } android.buildTypes { release { signingConfig = $("android.signingConfigs.release“) minifyEnabled true proguardFiles.add(file('proguard-rules.txt')) } } }
  • 30. #droidconIT android.ndk { moduleName = "TeapotNativeActivity" platformVersion = 17 cppFlags.add("-I${file("src/main/jni/native_app_glue")}".toString()) cppFlags.add("-I${file("src/main/jni/cpufeatures")}".toString()) cppFlags.add("-I${file("src/main/jni/ndk_helper")}".toString()) ldLibs.addAll(["android", "EGL", "GLESv2", "dl", "log"]) stl = "stlport_static" } build.gradle Native dependencies (with sources)
  • 31. #droidconIT android.sources { main{ jni { source { srcDir 'src/main/XXX'//folder srcDir 'src/main/YYY'//other folder exclude "**/not_this_one.c" //single file } } } } build.gradle Adding/Removing native sources to be compiled
  • 32. repositories { libs(PrebuiltLibraries) { myexternallib { headers.srcDir "src/main/jni/prebuilts/include" binaries.withType(SharedLibraryBinary) { sharedLibraryFile = file("src/main/jni/prebuilts/${targetPlatform.getName()}/libmyexternallib.so") } }}} android.ndk { moduleName = "TeapotNativeActivity" platformVersion = 17 ldLibs.addAll(["android", "EGL", "GLESv2", "dl", "log"]) stl = "stlport_static" } android.sources { main { jni { dependencies { library "myexternallib" linkage "dynamic" //dynamic is default / can be static too }}}} build.gradle Native dependencies (prebuilts)
  • 33. apply plugin: 'com.android.model.application' model { def versionCodeBase = 11; def versionCodePrefixes = ['armeabi': 1, 'armeabi-v7a': 2, 'arm64-v8a': 3, 'mips': 5, 'mips64': 6, 'x86': 8, 'x86_64': 9]; //... android.productFlavors { create ("armv7") { ndk.abiFilters.add("armeabi-v7a") versionCode = versionCodePrefixes.get("armeabi-v7a", 0) * 1000000 + versionCodeBase } create ("x86") { ndk.abiFilters.add("x86") versionCode = versionCodePrefixes.get("x86", 0) * 1000000 + versionCodeBase } } } build.gradle Multiple APKs (gradle-experimental)
  • 34. //project’s build.gradle: buildscript { … dependencies { classpath 'com.android.tools.build:gradle-experimental:0.6.0' classpath 'com.android.tools.build:gradle:2.0.0' } } //to keep debugging working, set this in the build.gradle that uses the stable plugin: android{ buildTypes.debug.jniDebuggable true } /! use the latest versions for both plugins, don’t mix older ones. build.gradle Mixing gradle stable and -experimental plugins
  • 35. Mixing gradle stable and -experimental plugins …and keep debugging working in AS:
  • 36. #droidconIT splits { abi { enable true reset() include 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a' universalApk true } } // map for the version code project.ext.versionCodes = ['armeabi': 1, 'armeabi-v7a': 2, 'arm64-v8a': 3, 'mips': 5, 'mips64': 6, 'x86': 8, 'x86_64': 9] applicationVariants.all { variant -> // assign different version code for each output variant.outputs.each { output -> output.versionCodeOverride = project.ext.versionCodes.get(output.getFilter(com.android.build.OutputFile.ABI), 0) * 1000000 + defaultConfig.versionCode } } build.gradle Multiple APKs (APK Splits – gradle-stable)
  • 37. Q&A@ph0b – ph0b.com – +XavierHallade
  • 38. #droidconIT Resources http://ph0b.com/new-android-studio-ndk-support/ https://github.com/googlesamples/android-ndk Watch for this issue to be resolved for fixing editing on Windows versions of AS: http://b.android.com/195483
  • 40. Multiple APKs and version codes handling Google Play* supports multiple APKs for the same application. What compatible APK will be chosen for a device entirely depends on the android:versionCode If you have multiple APKs for multiple ABIs, best is to simply prefix your current version code with a digit representing the ABI: 2310 3310 6310 7310 You can have more options for multiple APKs, here is a convention that will work if you’re using all of these: x86ARMv7 ARM64 X86_64
  • 41. #droidconIT Android.mk LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := hello-jni LOCAL_SRC_FILES := hello-jni.c include $(BUILD_SHARED_LIBRARY) Other useful variables: LOCAL_C_INCLUDES := ./headers/ LOCAL_EXPORT_C_INCLUDES := ./headers/ LOCAL_SHARED_LIBRARIES := module_shared LOCAL_STATIC_LIBRARIES := module_static Other predefined macros: BUILD_SHARED_LIBRARY, BUILD_STATIC_LIBRARY, PREBUILT_SHARED_LIBRARY, PREBUILT_STATIC_LIBRARY
  • 42. #droidconIT 43 Application.mk APP_PLATFORM := android-15 # <= minSDKVersion APP_CFLAGS := -O3 APP_STL := c++_shared APP_ABI := all # or all32, all64… APP_OPTIM := release # default NDK_TOOCLHAIN_VERSION := 4.8 # default
  • 43.
  • 44. import org.apache.tools.ant.taskdefs.condition.Os android.sources { main { jni { source { srcDirs = ['src/main/none'] } } jniLibs { source { srcDirs = ['src/main/libs'] } } } } task ndkBuild(type: Exec) { def ndkBuildExt = Os.isFamily(Os.FAMILY_WINDOWS) ? ".cmd" : "" commandLine "ndk-build${ndkBuildExt}", '-C', file('src/main').absolutePath } tasks.withType(JavaCompile) { compileTask -> compileTask.dependsOn ndkBuild } build.gradle Using Android.mk/Application.mk from Gradle