Android Native Apps Development

  • Published on
    24-May-2015

  • View
    1.016

  • Download
    2

Embed Size (px)

DESCRIPTION

Palestra ministrada por Eduardo Carrara no App Lab Android realizado no auditrio da Intel no dia 11 de Outubro de 2013.

Transcript

  • 1. Desenvolvendo Apps Nativas com NDK Eduardo Carrara de Araujo Software Analyst Intel Software

2. Agenda Entendendo o mundo Android* Nativo Conhecendo suas ferramentas Preparando-se para a batalha Mos obra! Quebrou! E agora? Q&A2 3. Entendendo o mundo Android* NativoINTEL CONFIDENTIAL 4. AppsHomeApplication FrameworkUser ExperienceAppsAs Engrenagens do Rob ContactsPhoneBrowserActivity ManagerWindows* ManagerContent ProvidersView SystemPackage ManagerTelephony ManagerResource ManagerLocation ManagerLibrariesNotification ManagerAndroid* RuntimeSurface ManagerMedia FrameworkSQLiteOpenGL* ESFreeTypeWebKitSGLMiddlewareSSLlibcCore LibrariesDalvik Virtual MachineOperating SystemLinux* Kernel4Display DriverCamera DriverFlash Memory DriverBinder (IPC) DriverKeypad DriverWiFi DriverAudio DriversPower Management 5. Nativo VS. Dalvik* O que uma aplicao Android* nativa? O que a Intel j faz por voc?Android Runtime Dalvik Virtual Machine Core Libraries5 6. Por qu utilizar cdigo nativo? Performance Jogos Processamento Grfico Criptografia Algoritmos de baixo nvel Acesso direto CPU, GPU e outros recursos de HW Reuso de cdigo E por que no utilizar? Performance Complexidade6 7. Conhecendo suas ferramentas7INTEL CONFIDENTIAL 8. Android* Native Development Kit (NDK) O que ? Conjunto de ferramentas que permitem a implementao de partes da aplicao Android utilizando cdigo nativo em linguagens como C ou C++. A interao entre o cdigo nativo e a app Android feita utilizando Java Native Interface (JNI). 9. Java Native Interface (JNI) O que ? Interface padro de programao para interoperabilidade entre bibliotecas nativas de uma plataforma e a mquina virtual Java. Quando usar? Acessar funcionalidades dependentes de plataforma no providas pela API padro do Java. Re-uso de cdigo. Pores de cdigo que precisam de tuning de performance.9 10. Fluxo de Desenvolvimento com NDK C/C++ CodendkbuildMakefileJava* callsGDB debugJNIAPP_ABI := all or APP_ABI := x86Android* ApplicationsJava Application SDK APIs Java FrameworkJNINative Libs Bionic C Library 10NDK APIs 11. Conhea os limites: A Bionic C Biblioteca C otimizada para a plataforma Android. Mais leve que a GNU C. No segue o padro POSIX. Suporte limitado pthreads. Acesso s propriedades do Android12 12. Preparando-se para a batalha14INTEL CONFIDENTIAL 13. Instalando o Android* NDK Baixe o SDK: http://developer.android.com/too ls/sdk/ndk Baixe o Intel Beacon Mountain: http://software.intel.com/enus/vcsource/tools/beaconmountai n Integre com o ADT e o CDT no Eclipse* 14. Adicionando Suporte Nativo (Eclipse*)16 15. Sem o piloto automtico Standard Android* Project Structure1. Create JNI folder for native sourcesNative Sources - JNI Folder 2. Reuse or create native c/c++ sources3. Create Android.mk MakefileNDK-BUILD will automatically create ABI libs folders.4. Build Native libraries using NDKBUILD script.17 16. Mos obra!INTEL CONFIDENTIAL 17. Hello NDK! Agora que temos um projeto pronto para utilizar cdigo nativo. Qual o prximo passo? Como integrar o cdigo Java com o C++?19 18. Integrando Funes Nativas com Java Declarar mtodos nativos em Java: public native String getHelloMessage(); A aplicao Java deve carregar a biblioteca antes de utiliz-la: System.loadLibrary("HelloNDK"); Implementar em sua biblioteca nativa os mtodos a serem utilizados pela aplicao Os pontos de entrada da biblioteca podem ser criados de duas formas: com a ferramenta Javah ou as registrando na funo JNI_onLoad na biblioteca.20 19. Javah Gera os header stubs apropriados para JNI partir das classes Java j compiladas. Example: > javah d jni classpath bin/classescom.example.hellojni.HelloJni Gera o arquivo: com_example_hellojni_HelloJni.h Com a definio: JNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_stringFromJNI(JN IEnv *, jobject);21 20. Javah... { ... tv.setText( stringFromJNI() ); ... } public native StringstringFromJNI();static { System.loadLibrary("hello-jni"); }jstring Java_com_example_hellojni_HelloJni_stringFromJNI(JNIEnv* env, jobject thiz ) { return (*env)->NewStringUTF(env, "Hello from JNI !"); } 21. JNI_onLoad Registro das funes JNI no carregamento da biblioteca. Utilizado nos mdulos nativos do AOSP. Sujeito a menos erros durante refatorao. Melhor local para lidar com o caching dereferncias objetos Java.23 22. JNI_onLoad Declare a funo C++ em sua lib: jstring stringFromJNI(JNIEnv* env, jobject thiz) { return env->NewStringUTF("Hello from JNI !"); } Crie o mapeamento de funes expostas: static JNINativeMethod exposedMethods[] = { {"stringFromJNI","()Ljava/lang/String;",(void*)stringFromJNI},} Utilize a ferramenta javap para obter a assinatura dos mtodos nativos: javap -s -classpath binclasses -p com.example.hellojni.HelloJni -> Signature: ()Ljava/lang/String;24 23. JNI_onLoad extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved) { JNIEnv* env; if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) return JNI_ERR; jclass clazz = env>FindClass("com/intel/applab/nativesample/NativeSample"); if(clazz==NULL) return JNI_ERR; env->RegisterNatives(clazz, exposedMethods, sizeof(exposedMethods)/sizeof(JNINativeMethod)); env->DeleteLocalRef(clazz); return JNI_VERSION_1_6; }25 24. Estamos prontos? No! Utilizar o arquivo Application.mk para descrever sua app: Diretrio: jni Descrever os mdulos necessrios Arquiteturas suportadas: ABI Arquivo opcional mas importante para garantir que seus mdulos nativos sejam compilados para diversas plataformas.APP_ABI := armeabi armeabi-v7a x86 Ou APP_ABI := all26 25. Build it! Utilizando Eclipse* Com a integrao ADT e NDK no Eclipse* basta compilar a app para gerar as bibliotecas e empacotar seu apk. Hardcore Mode Utilizar o script ndk_build para gerar os mdulos. No diretrio raz de sua app execute: $NDK/ndk_build27 26. Quebrou! E agora?INTEL CONFIDENTIAL 27. LogCat Mecanismo bsico de logs do Android. No NDK pode ser acessado pela API: int __android_log_print(int prio, const char *tag, const char *fmt, ...) Normalmente utilizado com a macro: #define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "APPTAG", __VA_ARGS__)) Exemplo LOGI("accelerometer: x=%f y=%f z=%f", x, y, z);29 28. Q&A31INTEL CONFIDENTIAL 29. Legal Disclaimer INFORMATION IN THIS DOCUMENT IS PROVIDED IN CONNECTION WITH INTEL PRODUCTS. NO LICENSE, EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE, TO ANY INTELLECTUAL PROPERTY RIGHTS IS GRANTED BY THIS DOCUMENT. EXCEPT AS PROVIDED IN INTEL'S TERMS AND CONDITIONS OF SALE FOR SUCH PRODUCTS, INTEL ASSUMES NO LIABILITY WHATSOEVER AND INTEL DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY, RELATING TO SALE AND/OR USE OF INTEL PRODUCTS INCLUDING LIABILITY OR WARRANTIES RELATING TO FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR INFRINGEMENT OF ANY PATENT, COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT. A "Mission Critical Application" is any application in which failure of the Intel Product could result, directly or indirectly, in personal injury or death. SHOULD YOU PURCHASE OR USE INTEL'S PRODUCTS FOR ANY SUCH MISSION CRITICAL APPLICATION, YOU SHALL INDEMNIFY AND HOLD INTEL AND ITS SUBSIDIARIES, SUBCONTRACTORS AND AFFILIATES, AND THE DIRECTORS, OFFICERS, AND EMPLOYEES OF EACH, HARMLESS AGAINST ALL CLAIMS COSTS, DAMAGES, AND EXPENSES AND REASONABLE ATTORNEYS' FEES ARISING OUT OF, DIRECTLY OR INDIRECTLY, ANY CLAIM OF PRODUCT LIABILITY, PERSONAL INJURY, OR DEATH ARISING IN ANY WAY OUT OF SUCH MISSION CRITICAL APPLICATION, WHETHER OR NOT INTEL OR ITS SUBCONTRACTOR WAS NEGLIGENT IN THE DESIGN, MANUFACTURE, OR WARNING OF THE INTEL PRODUCT OR ANY OF ITS PARTS. Intel may make changes to specifications and product descriptions at any time, without notice. Designers must not rely on the absence or characteristics of any features or instructions marked "reserved" or "undefined". Intel reserves these for future definition and shall have no responsibility whatsoever for conflicts or incompatibilities arising from future changes to them. The information here is subject to change without notice. Do not finalize a design with this information. The products described in this document may contain design defects or errors known as errata which may cause the product to deviate from published specifications. Current characterized errata are available on request. Contact your local Intel sales office or your distributor to obtain the latest specifications and before placing your product order. Copies of documents which have an order number and are referenced in this document, or other Intel literature, may be obtained by calling 1-800-548-4725, or go to: http://www.intel.com/design/literature.htm Silvermont and other code names featured are used internally within Intel to identify products that are in development and not yet publicly announced for release. Customers, licensees and other third parties are not authorized by Intel to use code names in advertising, promotion or marketing of any product or services and any such use of Intel's internal code names is at the sole risk of the user. Intel, Atom, Look Inside and the Intel logo are trademarks of Intel Corporation in the United States and other countries. *Other names and brands may be claimed as the property of others. Copyright 2013 Intel Corporation.32 30. Legal Disclaimer Roadmap Notice: All products, computer systems, dates and figures specified are preliminary based on current expectations, and are subject to change without notice. Intel Virtualization Technology (Intel VT) requires a computer system with an enabled Intel processor, BIOS, and virtual machine monitor (VMM). Functionality, performance or other benefits will vary depending on hardware and software configurations. Software applications may not be compatible with all operating systems. Consult your PC manufacturer. For more information, visit http://www.intel.com/g