android native apps hands on

41
Mão na Massa George H. Silva Android Community Manager

Upload: intel-software-brasil

Post on 24-May-2015

671 views

Category:

Technology


0 download

DESCRIPTION

Hands on facilitado por George Silva no App Lab Android realizado no auditório da Intel no dia 11 de Outubro de 2013.

TRANSCRIPT

Page 1: Android Native Apps Hands On

Mão na Massa

George H. SilvaAndroid Community Manager

Page 2: Android Native Apps Hands On

Agenda

• Introdução

• Ambiente de desenvolvimento

• Laboratório: mãos à obra

– Introdução ao laboratório & ferramentas Android*

– Portando uma aplicação para processador Intel® Atom™

– Criando uma aplicação baseada em NDK do início ao fim

• Resumo

Page 3: Android Native Apps Hands On

Agenda

• Introdução

• Ambiente de desenvolvimento

• Laboratório: mãos à obra

– Introdução ao laboratório & ferramentas Android*

– Portando uma aplicação para processador Intel® Atom™

– Criando uma aplicação baseada em NDK do início ao fim

• Resumo

Page 4: Android Native Apps Hands On

• Software baseado em Java roda dentro da máquina virtual Dalvik

• API padrão do Android Application Framework

• Independente de dispositivo

Figura: Arquitetura Android Fonte: android.com

Android App

Aplicação (App) Android*

A maioria dos Apps Android são independentes de plataforma

Page 5: Android Native Apps Hands On

Usando Código Nativo em Apps Android*

• JNI: interface entre código nativo (C/C++) e código dentro da Dalvik*

• Por que código nativo?

– Alto desempenho

– Reutilização de código

• Código nativo depende da arquitetura de hardware

• A maioria dos Apps no Android Market não contém código nativo

– Tais Apps são compatíveis com dispositivos com processador Atom™

Android App sem Código Nativo

Android Manifest

Dalvik optimized Java

Classes

Resources

Android App com Código Nativo

Android Manifest

Dalvik optimized Java

Classes

Resources

JNI/Native code libraries

Page 6: Android Native Apps Hands On

Agenda

• Introdução

• Ambiente de desenvolvimento

• Laboratório: mãos à obra

– Introdução ao laboratório & ferramentas Android*

– Portando uma aplicação para processador Intel® Atom™

– Criando uma aplicação baseada em NDK do início ao fim

• Resumo

Page 7: Android Native Apps Hands On

Ambiente de Desenvolvimento

− Java Development Kit (JDK)

− Android* SDK

− Android* NDK

− Opcional:

− Eclipse

− ADT - Android Development Tools

− CDT - C/C++ Development Tools

− Cygwin (Obrigatório para usar NDK no Windows*)

Page 8: Android Native Apps Hands On

Agenda

• Introdução

• Ambiente de desenvolvimento

• Laboratório: mãos à obra

– Introdução ao laboratório & ferramentas Android*

– Portando uma aplicação para processador Intel® Atom™

– Criando uma aplicação baseada em NDK do início ao fim

• Resumo

Page 9: Android Native Apps Hands On

Agenda

• Introdução

• Ambiente de desenvolvimento

• Laboratório: mãos à obra

– Introdução ao laboratório & ferramentas Android*

– Portando uma aplicação para processador Intel® Atom™

– Criando uma aplicação baseada em NDK do início ao fim

• Resumo

Page 10: Android Native Apps Hands On

Introdução ao Lab & Ferramentas do Android*

Objetivos

• Familiarização ao Lab e às ferramentas de desenvolvimento para Android*

• Como executar o emulador x86 para Android e verificar a execução de uma imagem do Android* ICS

• Como configurar e testar as ferramentas de desenvolvimento para Android*

Page 11: Android Native Apps Hands On

Configuração e teste inicial• SDK do Android e as demais ferramentas já estão instaladas

• Abra o terminal e verifique quais são as APIs (targets)Android instaladas.

1. Abra o terminal de comandos com duplo clique em LXTerminal2. Digite na linha de comando:

$ android list

2.3.7

4.0.4

Page 12: Android Native Apps Hands On

Criando um AVD ICS para emulador x861. Para iniciar o Android Virtual Device

(AVD) Manager,digite na linha de comando:

$ android avd

2. Para criar um novo AVD clique em New

3. Digite ics no campo Name

4. Selecione o Target:Android 4.0.3 – API Level 15 e CPU/ABI: Intel Atom (x86)

5. Clique em Create AVD.

6. Clique em OK.

Page 13: Android Native Apps Hands On

Executando o Emulador1. Para executar o emulador usando o AVD recém criado, digite na linha de

comando:

$ emulator-x86 –avd ics &

Page 14: Android Native Apps Hands On

Resumo

• Apresentamos o laboratório, o emulador x86 para Android e o ambiente de desenvolvimento

• Demonstramos o uso básico do emulador e outras ferramentas de desenvolvimento para Android. Agora o sistema está pronto para fazer os exercícios

Introdução ao Laboratório & Android*

Page 15: Android Native Apps Hands On

Agenda

• Introdução

• Ambiente de desenvolvimento

• Laboratório: mãos à obra

– Introdução ao laboratório & ferramentas Android*

– Portando uma aplicação para processador Intel® Atom™

– Criando uma aplicação baseada em NDK do início ao fim

• Resumo

Page 16: Android Native Apps Hands On

Lab 1: Portando a aplicação Terminal Emulator para processador Atom™

Objetivos:• Utilizar o emulador x86 Android na instalação, execução e depuração de Apps

• Aprender como identificar erros relacionados ao NDK

• Familiarizar-se com as ferramentas do NDK, adb e ant durante o porte de uma App simples baseado no NDK x86

• Demonstrar quão fácil é portar Apps Android baseadas no NDK ARM para a arquitetura x86

Conteúdo do diretório lab1:

• AndroidMarket-jackpal.androidterm-2.apk

• src – diretório com os arquivos fonte do Terminal Emulator

• solution – diretório com a versão final do lab 1

Page 17: Android Native Apps Hands On

Conteúdo do APK do Terminal Emulator

• APK: Android Application Package

• Descompacte o arquivo apk para ver seu conteúdo

• Apps usando NDK contém o diretório /lib com a interface JNI

– /lib/x86: biblioteca compilada para arquitetura x86

– /lib/armeabi: biblioteca compilada para Arm v5

– /lib/armeabi-v7: biblioteca compilada para Arm v7

Alguns APKs podem suportar múltiplas arquiteturas

Page 18: Android Native Apps Hands On

Use o adb para instalar o Terminal Emulator no emulador

1. Para mudar para o diretório lab1, digite:

$ cd ~/labs/lab1

2. Para instalar o App usando adb na linha, digite:

$ adb install AndroidMarket-jackpal-androidterm-

2.apk

3. Clique na icone recém instalado para abrir o App

Page 19: Android Native Apps Hands On

Use logcat para depurar problemas

Para usar o logcat para verificar erros, digite:$ adb shell logcat –t 50

Page 20: Android Native Apps Hands On

Use logcat para depurar problemas

Para desinstalar o App, digite:

$ adb uninstall jackpal.androidterm

Page 21: Android Native Apps Hands On

Conteúdo do arquivo de configuração antes de recompilar

1. Para mudar para o diretório com o código da App, digite:

$ cd ~/labs/lab1/src/Android-Terminal-Emulator

2. Para exibir o makefile e verificar as flags de compilação, digite:

$ cat jni/Android.mk

Figura: Android.mk

Page 22: Android Native Apps Hands On

Recompilando o App

1. Para recompilar o código fonte para x86 usando ndk-build, digite:

$ ndk-build APP_ABI=x86

2. Para atualizar o projeto Android usando ICS (API nível 15), digite:

$ android update project –-target “android-16” –-

path .

3. Para compilar o projeto para teste usando ant, digite:

$ ant debug

Page 23: Android Native Apps Hands On

Para instalar o App recém compilado usando adb, digite:

$ adb install bin/Term-debug.apk

Instale e execute a App no emulador

Page 24: Android Native Apps Hands On

Verificando a App no emulador

Para ver as últimas 20 mensagens através do logcat, digite:

$ adb shell logcat –t 20

Para desinstalar o App usando o adb, digite:

$ adb uninstall jackpal.androidterm

Page 25: Android Native Apps Hands On

Lab 1: Portando a aplicação Terminal Emulator para processador Atom™

Resumo:

• Aprendemos como instalar, executar e depurar Apps usando o emulador x86 para Android

• Aprendemos o processo de portar um App simples dependente do NDK para arquitetura x86

• Demonstramos que portar pode ser um processo simples e prático.

Page 26: Android Native Apps Hands On

Agenda

• Introdução

• Ambiente de desenvolvimento

• Laboratório: mãos à obra

– Introdução ao laboratório & ferramentas Android*

– Portando uma aplicação para processador Intel® Atom™

– Criando uma aplicação baseada em NDK do início ao fim

• Resumo

Page 27: Android Native Apps Hands On

Lab 2: criando uma App baseada em NDK do início ao f im

Objetivos:

• Criar e compilar uma biblioteca nativa compartilhada simples na arquitetura x86

• Criar e compilar uma App Android simples que use a biblioteca nativa

Page 28: Android Native Apps Hands On

1. Criando um projeto “Hello World”

1. Crie um diretório para o projeto, digitando:

$ mkdir -p ~/labs/lab2 && cd ~/labs/lab2

2. Para criar o projeto Android, digite:

$ android create project --target android-15 --activity

CPUIdApp --package com.example.cpuid --path .

Esqueleto do arquivo CPUIdApp.java que iremos alterar futuramente:

Page 29: Android Native Apps Hands On

2. Compilando e instalando o novo projeto1. Para poder testar o Hello World, primeiro execute o emulador, digitando:

$ emulator-x86 -avd ics &

2. Para compilar e instalatar o pacote (apk), digite:

$ ant debug && adb install –r bin/CPUIdApp-debug.apk

Page 30: Android Native Apps Hands On

Exemplo: código nativo para obter CPUID e extrair características

Page 31: Android Native Apps Hands On

3. Criando chamada à função nativa e carregando a biblioteca nativa

Para copiar o arquivo modificado do diretório com a solução, digite:

$ cp ../lab2sol/src/com/example/cpuid/CPUIdApp.java src/com/example/cpuid/CPUIdApp.java

Esqueleto Modificado

Page 32: Android Native Apps Hands On

4. Usando javah para gerar os headers JNI

1. Para recompilar gerando os arquivos class de Java, digite:$ ant debug

2. Para gerar os headers JNI através do javah , digite:

$ export JNI_CP=bin/classes:$ANDROID_SDK/platforms/android-16/android.jar$ javah -d jni -classpath $JNI_CP com.example.cpuid.CPUIdApp

O comando javah gera esse arquivo automáticamente

Page 33: Android Native Apps Hands On

5. Criando o arquivo stub nativo em C para invocação JNI

Para copiar esse arquivo do diretório de soluções, digite:

$ cp ../lab2sol/jni/com_example_cpuid_CPUIdApp.c

jni/com_example_cpuid_CPUIdApp.c

O stub contém a implementação da interface definida no header JNI:

Page 34: Android Native Apps Hands On

6. Copiando código C nativo com CPUID e makefile

1. Para copiar o código fonte nativo em C do CPUID, digite:

$ cp ../lab2sol/jni/cpuid.c jni/cpuid.c

2. Para copiar o arquivo de compilação da biblioteca compartilhada, digite:

$ cp ../lab2sol/jni/Android.mk jni/Android.mk

Page 35: Android Native Apps Hands On

7. Compilando e Instalando App Completo para Arquitetura x86

1. Para compilar a biblioteca nativa usando o NDK x86, digite

$ ndk-build APP_ABI=x86

2. Para recompilar o App e reinstalá-lo usando o ADB, digite:

$ ant debug && adb install –r bin/CPUIdApp-

debug.apk

Page 36: Android Native Apps Hands On

8. Executando a App CPUID pelo Emulador

Page 37: Android Native Apps Hands On

Resumo:

• Criamos um App Android usando código nativo do início ao fim.

• Aprendemos como definir e gerar chamadas nativas usando JNI

• Aprendemos como criar, reusar e compilar uma biblioteca nativa compartilhada para Apps Android

• Essa biblioteca compartilhada pode ser usada para criar algorítmos que exigem alto desempenho, permitir que Apps Android acessem código legado ou outros motvios.

Lab 2: Criando uma App baseado em NDK do início ao fim

Page 38: Android Native Apps Hands On

Resumo & Próximos Passos

• Apps padrão funcionam em qualquer aparelho Android contendo o processador Intel® Atom™

• Portar um App usando NDK é tão simple quanto recompilar (maior parte dos casos)

• Use o NDK x86 para diferenciar seus Apps tirando vantagem das capacidades do processador Intel® Atom™

Page 39: Android Native Apps Hands On

Legal DisclaimerINFORMATION 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.

• Intel processor numbers are not a measure of performance. Processor numbers differentiate features within each processor family, not across different processor families. Go to: http://www.intel.com/products/processor_number.

• 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 • Intel, Atom, Sponsors of Tomorrow 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 ©2012 Intel Corporation.

Page 40: Android Native Apps Hands On

Risk FactorsThe above statements and any others in this document that refer to plans and expectations for the second quarter, the year and the future are forward-looking statements that involve a number of risks and uncertainties. Words such as “anticipates,” “expects,” “intends,” “plans,” “believes,” “seeks,” “estimates,” “may,” “will,” “should” and their variations identify forward-looking statements. Statements that refer to or are based on projections, uncertain events or assumptions also identify forward-looking statements. Many factors could affect Intel’s actual results, and variances from Intel’s current expectations regarding such factors could cause actual results to differ materially from those expressed in these forward-looking statements. Intel presently considers the following to be the important factors that could cause actual results to differ materially from the company’s expectations. Demand could be different from Intel's expectations due to factors including changes in business and economic conditions, including supply constraints and other disruptions affecting customers; customer acceptance of Intel’s and competitors’ products; changes in customer order patterns including order cancellations; and changes in the level of inventory at customers. Uncertainty in global economic and financial conditions poses a risk that consumers and businesses may defer purchases in response to negative financial events, which could negatively affect product demand and other related matters. Intel operates in intensely competitive industries that are characterized by a high percentage of costs that are fixed or difficult to reduce in the short term and product demand that is highly variable and difficult to forecast. Revenue and the gross margin percentage are affected by the timing of Intel product introductions and the demand for and market acceptance of Intel's products; actions taken by Intel's competitors, including product offerings and introductions, marketing programs and pricing pressures and Intel’s response to such actions; and Intel’s ability to respond quickly to technological developments and to incorporate new features into its products. Intel is in the process of transitioning to its next generation of products on 22nm process technology, and there could be execution and timing issues associated with these changes, including products defects and errata and lower than anticipated manufacturing yields. The gross margin percentage could vary significantly from expectations based on capacity utilization; variations in inventory valuation, including variations related to the timing of qualifying products for sale; changes in revenue levels; segment product mix; the timing and execution of the manufacturing ramp and associated costs; start-up costs; excess or obsolete inventory; changes in unit costs; defects or disruptions in the supply of materials or resources; product manufacturing quality/yields; and impairments of long-lived assets, including manufacturing, assembly/test and intangible assets. The majority of Intel’s non-marketable equity investment portfolio balance is concentrated in companies in the flash memory market segment, and declines in this market segment or changes in management’s plans with respect to Intel’s investments in this market segment could result in significant impairment charges, impacting restructuring charges as well as gains/losses on equity investments and interest and other. Intel's results could be affected by adverse economic, social, political and physical/infrastructure conditions in countries where Intel, its customers or its suppliers operate, including military conflict and other security risks, natural disasters, infrastructure disruptions, health concerns and fluctuations in currency exchange rates. Expenses, particularly certain marketing and compensation expenses, as well as restructuring and asset impairment charges, vary depending on the level of demand for Intel's products and the level of revenue and profits. Intel’s results could be affected by the timing of closing of acquisitions and divestitures. Intel's results could be affected by adverse effects associated with product defects and errata (deviations from published specifications), and by litigation or regulatory matters involving intellectual property, stockholder, consumer, antitrust, disclosure and other issues, such as the litigation and regulatory matters described in Intel's SEC reports. An unfavorable ruling could include monetary damages or an injunction prohibiting Intel from manufacturing or selling one or more products, precluding particular business practices, impacting Intel’s ability to design its products, or requiring other remedies such as compulsory licensing of intellectual property. A detailed discussion of these and other factors that could affect Intel’s results is included in Intel’s SEC filings, including the report on Form 10-K for the year ended Dec. 31, 2011.

Rev. 4/17/12

Page 41: Android Native Apps Hands On

Thank You