O Android NDK é a ferramenta que permite a utilização de código nativo (C/C++) em sua aplicação Android. Nesta apresentação conheça alguns usos interessantes do NDK, as vantagens e desvantagens de utilizá-lo, além de como começar a usar esta ferramenta com o Android Studio.
2. Intel Developers Relations Division 2
Agenda
O Android NDK
Será que você o usa e não sabe?
Cuidados com a Interface Binária
Começando com o Android Studio + gradle-experimental
Perguntas?
4. Intel Developers Relations Division 4
"O Android NDK é um conjunto de ferramentas que
permitem implementar partes de sua aplicação utilizando
linguagens de código nativas como C e C++."
- NDK Android Developers Portal
5. Intel Developers Relations Division 5
e talvez você já esteja fazendo isso...
... vamos explorar alguns usos interessantes do NDK.
7. Intel Developers Relations Division 7
Game Engines
Outras+…
*Other names and brands may be claimed as the property of others.
8. Intel Developers Relations Division 8
Visão Computacional
• Filtros lineares e não lineares de imagens.
• Tranformações Geométricas de imagens.
• Estimativa de Movimentos em videos.
• Subtração de Fundo em videos.
• Rastreamento de objetos.
• ...
Outras: Cardboard-SDK, Vuforia, Layar, LibCCV,
Wikitude ...
OpenCV.org
*Other names and brands may be claimed as the property of others.
9. Intel Developers Relations Division 9
Desenvolvimento Cross Platform
*Other names and brands may be claimed as the property of others.
10. Intel Developers Relations Division 10
Outros usos e Bibliotecas
Realm
Swift
Libpng
Intel TBB
Intel IPP
Libcairo and libpixman
Libsonic
Busybox
Speex
FFMpeg
OpenSSL
Lua
...
*Other names and brands may be claimed as the property of others.
11. Intel Developers Relations Division 11
Tantas aplicações bacanas!
Então podemos utilizar o
NDK para TUDO?!
13. Intel Developers Relations Division
Fonte: Using the NDK Performantly (Big Android BBQ 2015)
15
Visão Geral da Arquitetura
App Code
Classes do Framework
Runtime
Bibliotecas do
Sistema
Kernel Linux
JNI
Suas Bibliotecas
ABI Estável
14. Intel Developers Relations Division 17
Na Prática...
Microchip Icon – Icon Finder.
App
0010011100
0011100111
x86
ARM
MIPS
O seu código:
• Mais próximo do HW
• Dependente de Plataforma
Você deve se preocupar
com isso!
16. Intel Developers Relations Division 19
3 Regras de Ouro para adoção do NDK
1
2
3 Código legado que deve ser reaproveitado e muito caro para portar.
Problemas Específicos de performance.
Funcionalidades e Experiências que exigem performance.
17. Intel Developers Relations Division 20
3 (Principais) Barreiras para adoção do NDK
1
2
3 Ganhos de Performance não são garantidos.
Complexidade de Implementação e Manutenção.
Dependência de Plataforma e Compatibilidade.
18. Intel Developers Relations Division 21
Podemos, mas não devemos usar o NDK para tudo.
Logo ...
Ainda interessado?
Tome a “pílula vermelha” e vamos te mostrar o quão
longe isso vai...
20. Intel Developers Relations Division 23
Conceitos Fundamentais: Java Native Interface (JNI)
Define como o Java e o código nativo irão conversar.
Java C / C++
• Carregar a lib com:
• System.loadLibrary()
• Definição de Métodos Nativos:
• Palavra reservada native
• Incluir o header do JNI:
• #include <jni.h>
• Utilizar tipos específicos do JNI:
• jstring, jint, jboolean, etc.
• Variáveis Especiais:
• JNIEnv*, JavaVM*
21. Intel Developers Relations Division 24
JNI: Mapeamento de Métodos Java -> C / C++
A Função no C / C++ deve:
Usar e retornar primitivas e objetos Java JNI:
Seguir o padrão de nomenclatura:
Ou ser regitrada manualmente:
jint xxx(JNIEnv* env, jobject instance, ...) { ... }
Java_com_example_hellojni_HelloWorldJni_method
JNIEnv->RegisterNatives();
22. Intel Developers Relations Division 25
JNI: Exemplo
Java
C / C++
public class HelloWorldJNI {
static {
System.loadLibrary("hello-jni");
}
public native String getHelloWorldStringFromJNI();
}
#include <jni.h>
jstring
Java_com_example_hellojni_HelloWorldJNI_getHelloWorldStringFromJNI(JNIEnv *env, jobject instance) {
return (*env)->NewStringUTF(env, "Hello World!");
}
23. Intel Developers Relations Division 26
Old but Gold
Compilando Apps NDK no estilo clássico.
JNICode
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := hello-jni
LOCAL_SRC_FILES := hello-jni.c
include $(BUILD_SHARED_LIBRARY)
APP_ABI := all
jni/Android.mk jni/Application.mk
24. Intel Developers Relations Division 27
Old but Gold
ndk_build script
Compilando Apps NDK no estilo clássico.
25. Intel Developers Relations Division 28
Old but Gold
Empacotando Apps NDK no estilo
“quase” clássico.
• Adicione as libs no diretório jniLibs.
• Crie as interfaces java – jni.
• Para pre-builts é só isso.
• Para compilar a partir do source é
um pouco mais complicado mas
possível.
26. Intel Developers Relations Division 29
Limitações
• Debug não é possível no AS. Necessário o uso do ndk-gdb e/ou Eclipse.
• Suporte do plugin do gradle atual foi marcado como deprecated (ouch).
29. Intel Developers Relations Division 32
Avisos Importantes
• Utilizaremos a versão experimental do android gradle plugin.
• Integração com Android Studio melhorou mas ainda é instável e possui bugs.
• No Windows há problemas com o editor e/ou build que dificultam/impedem
o uso. (Issues 195483 e 204552).
• A documentação é praticamente inexistente ou incompleta.
30. Intel Developers Relations Division 33
Integração com AS
Instalação e
configuração do
NDK integrados ao
android studio.
38. Intel Developers Relations Division 41
gradle-experimental
• Ainda é possível:
• Configurar bibliotecas pré-compiladas;
• Adicionar flags de compilação (gerais e por flavor);
• A documentação atual geralmente não acompanha os releases, portanto:
• Fique de olho nos NDK Samples para referências!
39. Intel Developers Relations Division 42
Pensamentos Finais
Ao usar NDK, direta ou indiretamente, adicione
suporte a maior quantidade possível de
plataformas.
Use o NDK sabiamente: teste, faça benchmarks
e garanta que ele é a solução adequada ao seu
problema.
Acompanhe e teste o plugin experimental do
gradle para NDK!
45. Intel Developers Relations Division
Security features enabled by Intel® AMT require an enabled chipset, network hardware and software and a corporate network connection. Intel AMT may not be available or
certain capabilities may be limited over a host OS-based VPN or when connecting wirelessly, on battery power, sleeping, hibernating or powered off. Setup requires
configuration and may require scripting with the management console or further integration into existing security frameworks, and modifications or implementation of new
business processes. For more information, see http://www.intel.com/technology/manage/iamt.
WiMAX connectivity requires a WiMAX enabled device and subscription to a WiMAX broadband service. WiMAX connectivity may require you to purchase additional software
or hardware at extra cost. Availability of WiMAX is limited, check with your service provider for details on availability and network limitations. Broadband performance and
results may vary due to environment factors and other variables. See www.intel.com/go/wimax for more information.
Intel® My WiFi Technology is an optional feature and requires additional software and a Centrino® wireless adapter. Wi-Fi devices must be certified by the Wi-Fi Alliance for
802.11b/g/a in order to connect. See mywifi.intel.com for more details.
Hyper-Threading Technology requires a computer system with a processor supporting HT Technology and an HT Technology-enabled chipset, BIOS and operating system.
Performance will vary depending on the specific hardware and software you use. For more information including details on which processors support HT Technology, see
here
No system can provide absolute security under all conditions. Requires an enabled chipset, BIOS, firmware and software and a subscription with a capable Service
Provider. Consult your system manufacturer and Service Provider for availability and functionality. Intel assumes no liability for lost or stolen data and/or systems or any
other damages resulting thereof. For more information, visit http://www.intel.com/go/anti-theft Intel® Turbo Boost Technology requires a PC with a processor with Intel
Turbo Boost Technology capability. Intel Turbo Boost Technology performance varies depending on hardware, software and overall system configuration. Check with your
PC manufacturer on whether your system delivers Intel Turbo Boost Technology. For more information, see http://www.intel.com/technology/turboboost
Requires an Intel® Wireless Display enabled PC, TV Adapter, and compatible television. Available on select Intel® Core processors. Does not support Blu-Ray or other
protected content playback. Consult your PC manufacturer. For more information, see www.intel.com/go/wirelessdisplay
(Built-in Visuals) Available on the 2nd gen Intel® Core™ processor family. Includes Intel® HD Graphics, Intel® Quick Sync Video, Intel® Clear Video HD Technology, Intel® InTru™
3D Technology, and Intel® Advanced Vector Extensions. Also optionally includes Intel® Wireless Display depending on whether enabled on a given system or not. Whether you
will receive the benefits of built-in visuals depends upon the particular design of the PC you choose. Consult your PC manufacturer whether built-in visuals are enabled on
your system. Learn more about built-in visuals at http://www.intel.com/technology/visualtechnology/index.htm.
Legal Notices and Disclaimers, cont.