Quantcast
Channel: Intel Developer Zone Articles
Viewing all 183 articles
Browse latest View live

Velocizzare l'emulatore Android* sull'architettura Intel®

$
0
0

Sunto:

Se siete uno sviluppatore di Android* che è insoddisfatto delle prestazioni dell'emulatore Android, allora questo documento fa per voi. Sappiamo delle continue lamentele degli sviluppatori di Android in merito all'emulatore che è lento e complesso da utilizzare. La situazione è però cambiata. Se usate un computer sufficientemente aggiornato con un processore Intel® che ha attivata la Intel® Virtualization Technology e che esegue Microsoft Windows* o Apple Mac OS*, potete allora usare Intel® Hardware Accelerated Execution Manager (Intel® HAXM) o KVM per Linux*, che è un modo semplice per accelerare notevolmente l'emulatore Android e, di conseguenza, le attività di test e debug delle applicazioni Android. Questo documento spiega tutti i passaggi richiesti per accelerare l'emulatore e come utilizzarlo. Spiega quindi come usare l'NDK per compilare il codice nativo x86 e il modo corretto per inviare gli APK contenenti le librerie native x86 allo store Google Play. Intel HAXM è anche usato per accelerare l'emulatore Tizen*, ma questo è un argomento che esula dall'ambito di questa documentazione. Per maggiori informazioni in merito, visitare tizen.org nella sezione dell'SDK.

Indice

1. Introduzione
2. Installazione
2.1. Prerequisiti
2.2. Installazione in Windows
2.3. Installazione in Linux
2.3.1. Installazione di KVM
2.4. Creazione di un AVD (Android* Virtual Device)
3. Metodologie ottimali
3.1. Testare l'applicazione con l'emulatore di Eclipse
3.2. Inviare più pacchetti APK per ABI diverse oppure inviare dei fat binary a Google Play
3.3. Compilare l'NDK per x86
3.3.1. Aggiungere il percorso dell'NDK alla variabile d'ambiente
3.3.2. Compilazione con l'NDK
3.3.3. Un altro modo per compilare con l'NDK

1. Introduzione

Questo documento offre le indicazioni per eseguire l’installazione di Intel® Hardware Accelerated Execution Manager (Intel® HAXM), un motore di virtualizzazione basato su hardware (hypervisor) che usa la Intel® Virtualization Technology (Intel® VT) per accelerare lo sviluppo Android* in Windows*. Spiega anche come configurare una macchina virtuale basata su kernel (KVM) e basata su hardware in Linux* e le metodologie ottimali per la compilazione nativa e l'invio di applicazioni allo store Google Play per x86.

2. Installazione

2.1. Prerequisiti

  • È necessario che l'Android SDK sia installato.
  • Il computer deve avere un processore Intel con il supporto per Intel VT-x, EM64T e la funzionalità Execute Disable(XD) Bit abilitata nel BIOS.

2.2. Installazione in Windows

Dopo aver installato l'Android SDK, aprire SDK Manager. È possibile trovare Intel HAXM nella sezione delle funzionalità aggiuntive.

Selezionare la casella e fare clic sul pulsante ‘Install packages…’ per installare il pacchetto. Non lasciarsi però trarre in inganno dallo stato visualizzato (‘Installed’), perché in realtà l'installazione non è avvenuta. L'SDK infatti copia sul computer solo il file eseguibile di Intel HAXM e sta a voi installarlo.

Per installare l'eseguibile di Intel HAXM, ricercare nel disco rigido il file IntelHaxm.exe (o IntelHAXM.dmg in Mac OS X). Se si sono lasciate invariate le impostazioni predefinite, il file dovrebbe trovarsi in C:\Programmi\Android\android-sdk\extras\Intel\Hardware_Accelerated_Execution_Manager\IntelHaxm.exe.

Intel HAXM funziona solo in combinazione con una delle immagini dei sistemi x86 basati sul processore Intel® Atom™, che sono disponibili per Android 2.3.3 (API 10), 4.0.3 (API 15), 4.1.2 (API 16), 4.2.2 (API 17). Queste immagini di sistema Intel possono essere installate esattamente come si fa per le immagini basate su ARM tramite l'SDK manager.

Quando si fa clic sull'eseguibile IntelHaxm, appare una schermata di benvenuto simile alla seguente:

È possibile regolare la quantità di memoria RAM da allocare a Intel HAXM. Dopo questa operazione, fare clic su Next. La schermata successiva conferma l'allocazione della memoria. Se tutte le informazioni sono quelle desiderate, fare clic su Install.

Per poter installare Intel HAXM, è necessario che Intel VT-x sia abilitato nel BIOS, altrimenti durante l'installazione sarà visualizzato un errore simile al seguente:

Se si riceve questo errore, entrare nel BIOS ed abilitare la funzione.

La seconda opzione per scaricare Intel HAXM e l'immagine dell'emulatore del sistema x86 è di andare direttamente al sito Web http://software.intel.com/it-it/android e da lì scaricare i componenti necessari.

2.3. Installazione in Linux

I passaggi per accelerare l'emulatore Android per Linux sono diversi da quelli per Windows e Mac OS X perché Intel HAXM non è compatibile con Linux ed è perciò necessario usare una macchina virtuale basata su kernel (KVM). I passaggi descritti di seguito sono stati eseguiti usando Ubuntu* 12.04 e potrebbero variare leggermente con altre distribuzioni Linux.

Come visto per Windows (e Mac OS X), è prima necessario scaricare l'Android SDK dal sito per sviluppatori Android. Si troverà un pacchetto ADT (Android Developer Tool) che contiene sia Eclipse* IDE che l'Android SDK. Scaricare il file zip ed estrarlo sul computer Linux. Accertarsi di usare la versione corretta per la propria distribuzione Linux, a 32 bit o a 64 bit. Lo si può verificare facilmente usando il comando:

file /sbin/init

Prima di iniziare a installare i pacchetti richiesti per KVM, si consiglia di accertarsi di avere l'ultimo repository digitando:

sudo apt-get update

2.3.1. Installazione di KVM

Per installare ed eseguire KVM, che è una soluzione completa di virtualizzazione per Linux su hardware x86 (ad esempio, Intel VT), è prima necessario controllare che la CPU supporti la virtualizzazione dell'hardware digitando:

egrep –c ‘(vmx|svm)’ /proc/cpuinfo

Se il risultato è 0, significa che la CPU non supporta la virtualizzazione dell'hardware, che è necessaria per eseguire la KVM. Se il risultato è 1 o un valore superiore, significa che si può procedere senza problemi, ma occorre sempre verificare che sia abilitata nel BIOS (vedere la Sezione 2.2).

Quindi si dovrà installare KVM, se non lo si è già installato. Si può verificare se il processore supporta KVM digitando:

kvm-ok

Se KVM è installato, sarà visualizzato questo messaggio:

"INFO: Your CPU supports KVM extensions
INFO: /dev/kvm exists
KVM acceleration can be used"

Altrimenti, sarà necessario andare nel BIOS e attivare Intel VT se appare il seguente messaggio:

"INFO: KVM is disabled by your BIOS
HINT: Enter your BIOS setup and enable Virtualization Technology (VT),
and then hard poweroff/poweron your system
KVM acceleration can NOT be used"

Nel passaggio successivo si installa la KVM e alcuni altri pacchetti necessari. A tal fine, digitare

sudo apt-get install qemu-kvm libvirt-bin ubuntu-vm-builder bridge-utils

Nella finestra successiva, selezionare No configuration se si desidera lasciare immutata la propria configurazione:

Quindi, aggiungere il proprio utente al gruppo KVM e al gruppo libvirtd. A tal fine, digitare:

sudo adduser proprio_nome_utente kvm
sudo adduser proprio_nome_utente libvirtd

Dopo l'installazione, eseguire nuovamente l'accesso cosicché le modifiche abbiano effetto. È possibile testare l'installazione digitando:

sudo virsh -c qemu:///system list

Si è ora pronti a continuare con il passaggio successivo in cui si crea ed esegue il dispositivo virtuale Android (AVD). La procedura è la stessa per Linux e Windows.

2.4. Creazione di un AVD (Android* Virtual Device)

Dopo aver installato l'SDK e Intel HAXM (o KVM in Linux), si può creare un dispositivo virtuale con emulazione accelerata da hardware. Al tal fine, andare in AVD Manager e creare un nuovo dispositivo. Accertarsi di selezionare Intel Atom (x86) come CPU/ABI. L'opzione appare nel menu a discesa solo se è installata l'immagine di sistema Intel x86. Per una maggiore fluidità della grafica, attivare l'emulazione della GPU mentre si crea l'AVD.

Fare clic su New e creare il dispositivo AVD x86. Accertarsi di selezionare un'API che sia supportata dalle immagini dei sistemi x86, di aver impostato l'opzione CPU/ABI a x86 e di aver abilitata l'emulazione della GPU (OpenGL ES*). Fatto questo, fare clic su Create AVD per creare il dispositivo virtuale Android.

È possibile avviare l'AVD x86 facendo clic su Start e quindi su Launch.

Se l'installazione riesce, all'avvio dell'emulatore appare una finestra di dialogo indicante che Intel HAXM è eseguito in modalità virtuale veloce.

Per accertarsi ulteriormente che l'immagine utilizzata sia di un sistema x86, è sempre possibile controllare le informazioni riportate in ‘About phone’ nell'emulatore.

L'aumento delle prestazioni che si osserverà con Intel HAXM o KVM dipende dal PC utilizzato, dall'unità, dalla memoria e da altri fattori, ma dovrebbe essere di un ordine di grandezza di 5-10 volte. La schermata seguente mostra il confronto tra un AVD abilitato x86/HAXM e un AVD basato su ARM. Il dispositivo AVD x86 si avvia nello schermo bloccato nel giro di 15 secondi mentre il dispositivo AVD non di Intel impiega 40 secondi, che è una differenza notevole.

[Con Intel HAXM (o KVM) si dovrebbe rilevare un aumento delle prestazioni di 5-10 volte, in base alla configurazione del sistema. Il software e i carichi di lavoro utilizzati nei test delle prestazioni potrebbero essere stati ottimizzati per le prestazioni solo sui microprocessori Intel. I test delle prestazioni, come SYSmark* e MobileMark*, sono misurati usando computer, componenti, software, operazioni e funzioni specifici. Qualunque modifica a questi fattori potrebbe causare variazioni nei risultati. Per valutare in modo più completo i prodotti considerati per l'acquisto, si consiglia di consultare altre informazioni e test delle prestazioni, incluse le prestazioni del prodotto quando usato insieme ad altri prodotti. Configurazione: in questo caso per i test è stato usato Mac Book Pro. Per maggiori informazioni andare a http://www.intel.com/performance”]

3. Metodologie ottimali

3.1. Testare l'applicazione con l'emulatore di Eclipse

Intel HAXM può essere utilizzato per velocizzare l'emulatore durante i test, sia che si tratti di un'applicazione basata su NDK che di un'applicazione Dalvik*. Se si sta sviluppando con Eclipse, seguire questa semplice procedura per accertarsi di usare Intel HAXM quando si avvia l'emulatore.

Accertarsi innanzitutto di creare l'AVD secondo le istruzioni date nel passaggio 2. Se l'AVD è pronto, andare a Run As -> Run Config come mostrato qui di seguito:

Dovrebbe aprirsi una pagina simile a questa:

In questa pagina è possibile scegliere l'AVD desiderato selezionando la casella corrispondente. Dopo aver creato l'AVD e impostata la configurazione, iniziare a compilare il progetto ed eseguirne il debug con l'emulatore selezionando Run As -> Android Application. In questo modo l'AVD accelerato da hardware si avvia automaticamente.

Dopo che l'AVD si è avviato, dovrebbe apparire la schermata iniziale dell'applicazione (occorre prima sbloccare lo schermo).

3.2. Inviare più pacchetti APK per ABI diverse oppure inviare dei fat binary a Google Play

In passato si sarebbe inviato un fat binary dell'applicazione sviluppata contenente tutte le librerie e i file NDK, senza poter differenziare tra le diverse architetture. In questo caso gli utenti avrebbero scaricato l'APK completo contenente anche i file non rilevanti per le architetture specifiche, ad esempio gli utenti x86 si sarebbero ritrovati con del codice ARM e viceversa. Lo svantaggio di questo metodo è che il fat binary ha dimensioni notevoli e l'utente è obbligato a scaricare una gran quantità di dati che non sono applicabili al dispositivo. È in genere accettabile se l'APK ha dimensioni inferiori ai 10-20 MB.

Intel e Google hanno implementato un meccanismo di filtro della CPU che, se ci si attiene al codice di versione consigliato mostrato qui di seguito, permette di inviare più APK contenenti le diverse librerie specifiche per ciascuna architettura.

La prima cifra si riferisce all'ABI, ad esempio 6 si riferisce all'architettura x86. Le cifre successive si riferiscono al livello di API che si intende utilizzare (11), alle dimensioni dello schermo (13) e quindi al numero di versione dell'applicazione (3.1.0).

Accertarsi che il numero di versione dell'applicazione contenga almeno 8 cifre e di assegnare le prima cifra più elevata alla versione x86. Nell'esempio precedente, si userebbe 6 per indicare x86, 2 per ARMv7 e 1 per ARMv5TE. In questo modo si permette che le versioni x86 siano quelle preferite dai dispositivi x86 e le versioni ARM siano quelle preferite dai dispositivi ARM.

Attenendosi a queste linee guida si assicura che gli utenti ottengano le prestazioni migliori dal dispositivo che usano. Si evita inoltre che gli utenti, a causa di errori di traduzione di codice, tentino di eseguire le applicazioni su dispositivi specifici.

Ulteriori informazioni sono reperibili all'indirizzo http://software.intel.com/it-it/articles/google-play-supports-cpu-architecture-filtering-for-multiple-apk.

3.3. Compilare l'NDK per x86

Questa sezione descrive come compilare la parte per x86 dell'NDK dell'applicazione.

Affinché l'applicazione basata su NDK possa essere eseguita su un dispositivo AVD x86 è necessario compilare la libreria NDK per l'architettura x86. A tal fine, seguire questa semplice procedura:

Aprire un prompt dei comandi e andare nella cartella dei file NDK, come mostrato sotto:

Accertarsi di aver impostato il percorso della variabile d'ambiente in modo da poter utilizzare lo script ndk-build da qualsiasi posizione.

3.3.1. Aggiungere il percorso dell'NDK alla variabile d'ambiente

Per impostare la variabile d'ambiente per l'NDK, fare clic su Computer e selezionare Properties. Andare alle proprietà di sistema Advanced e individuare le variabili d'ambiente (Environment Variables). Selezionare Path e fare clic su Edit. Alla fine della stringa ‘Variable Value’, aggiungere il percorso alla propria cartella principale dell'NDK, quella che contiene il file ndk-build.cmd come mostrato nell'immagine seguente:

3.3.2. Compilazione con l'NDK

Dal prompt dei comandi andare alla cartella dell'NDK ed eseguire:

ndk-build APP_ABI:=all

Il file NDK sarà eseguito per ciascuna architettura disponibile, ad esempio ARMv5TE, ARMv7, x86 e mips.

Per compilare per architetture specifiche, sostituire ‘all’ con le diverse architetture. Ad esempio:

ndk-build APP_ABI:=armeabi armeabi-v7a x86 mips

Accertarsi di aggiornare il progetto in Eclipse affinché siano acquisite le ultime impostazioni, come ad esempio le ultime cartelle create dallo script ndk-build. Nella cartella libs dei progetti dovrebbero ora essere presenti quattro cartelle, una per ciascuna architettura.

Si è ora pronti a usare l'AVD x86 con l'applicazione NDK.

3.3.3. Un altro modo per compilare con l'NDK

Un altro modo per compilare il codice nativo per tutte le architetture, inclusa l'architettura x86, è di modificare il file Application.mk che si trova nella cartella jni. Se il file Application.mk non è presente, lo si può creare e aggiungervi l'istruzione seguente:

APP_ABI:=armeabi armeabi-v7a x86 mips

In questo modo, quando si esegue il file batch, ad esempio lo script ndk-build, saranno compilate le librerie per tutte le architetture disponibili.

Inoltre, per semplificare l'uso, invece di elencare tutte le architetture basta indicare ‘all’:

APP_ABI:=all


Creazione e porting di applicazioni Android* basate su NDK per l'architettura Intel

$
0
0

Obiettivo

Quest'articolo è un'introduzione per principianti sulla creazione di applicazioni native Android* (basate su NDK) per i dispositivi basati sull'architettura Intel®. Tratta anche del porting verso i dispositivi basati sull'architettura Intel di applicazioni NDK Android originariamente create per dispositivi basati su altre architetture. Analizzeremo due scenari, uno per mostrare il processo completo di creazione di una semplice applicazione Android* basata su NDK e l'altro per dimostrare un semplice processo di porting di un'applicazione Android basata su NDK affinché sia utilizzabile su dispositivi basati sull'architettura Intel.

Indice

1. Introduzione

2. Creazione di un'applicazione Android basata su NDK per dispositivi basati sull'architettura Intel - Procedura dettagliata di una semplice applicazione

a. Creare un progetto Android predefinito
b. Richiamare il codice nativo dai file sorgente Java
c. Usare javah per generare gli stub dell'header JNI per il codice nativo
d. Compilare il codice nativo con l'NDK per l'architettura Intel
e. Ricompilare, installare ed eseguire l'applicazione Android NDK per l'architettura Intel

3. Uso degli strumenti dell'NDK x86 per eseguire il porting verso dispositivi basati sull'architettura Intel di applicazioni NDK esistenti

4. Riepilogo

Introduzione

È possibile incorporare codice nativo nelle applicazioni Android usando gli strumenti del Native Development Kit (NDK). Questo permette agli sviluppatori di riusare il codice legacy, codificare per l'hardware di basso livello o differenziare le applicazioni sfruttando funzioni che altrimenti non sarebbero ottimali o disponibili.

Questo articolo è un'introduzione elementare su come creare, dall'inizio alla fine, applicazioni basate su NDK per l'architettura Intel e include anche dei semplici casi di utilizzo per eseguire il porting di applicazioni esistenti basate su NDK verso dispositivi basati sull'architettura Intel. Sarà descritto dettagliatamente un semplice scenario di sviluppo di un'applicazione per dimostrare il processo.

Si presume che l'ambiente di sviluppo Android sia già installato, compresi l'Android SDK, l'Android NDK e l'emulatore x86 configurato per testare le applicazioni. Per ulteriori informazioni, si prega di fare riferimento alla sezione della comunità Android nel sito Web di Intel. Per mantenere un ambiente di sviluppo semplice, nella maggior parte dei casi si useranno strumenti della riga di comando Linux*.

Creazione di un'applicazione Android basata su NDK per dispositivi basati sull'architettura Intel - Procedura dettagliata di una semplice applicazione

Si presuma di avere del codice legacy che usa C e il linguaggio assembly per analizzare l'istruzione CPUID (per maggiori informazioni su CPUID, consultare http://it.wikipedia.org/wiki/CPUID*). Qui di seguito è il listato del file sorgente del nostro codice C “legacy” di esempio cpuid.c (che è solo a scopo dimostrativo).

Desideriamo richiamare cpuid_parse dalla nostra applicazione Android (solo a scopo dimostrativo; la funzione cpuid_parse prevede un buffer preallocato) e visualizzare l'output all'interno dell'applicazione.

Qui di seguito è descritta la procedura dettagliata per creare l'applicazione Android dall'inizio alla fine e usare il codice nativo legacy visto in precedenza.

1. Creare un progetto Android predefinito

Android SDK ha strumenti della riga di comando che consentono di generare una struttura di progetto predefinita per un'applicazione hello world tipica. Creeremo innanzitutto un progetto predefinito, quindi modificheremo i file sorgente Java in modo da poter aggiungere chiamate JNI e codice nativo.

Nella schermata precedente, abbiamo prima creato una directory chiamata labs/lab2 e usato lo strumento della riga di comando “android” per generare il progetto predefinito. Abbiamo specificato android-15 come livello di API e chiamato la nostra applicazione “CPUIdApp” con package com.example.cpuid.

Abbiamo quindi usato lo strumento della riga di comando “ant” per creare il progetto in modalità di debug e installare usando “adb” (o reinstallare se già esistente nell'emulatore e nella destinazione). Si presume che abbiate già un emulatore o un dispositivo collegato e che sia l'unico dispositivo che viene elencato nell'output del comando “adb devices”.

La schermata seguente mostra l'emulatore Android x86 con ICS dopo avere completato il processo precedente.

Facendo clic sull'applicazione, viene visualizzato l'output predefinito hello world dell'applicazione. Modificheremo ora l'applicazione per l'uso del codice nativo.

2. Richiamare il codice nativo dai file sorgente Java

Il progetto Android predefinito genera i file sorgente Java per un progetto hello world tipico con lo spazio dei nomi del pacchetto dato (es. com.example.cpuid). La schermata seguente mostra il codice sorgente generato per il file sorgente Java principale.

Per usare il codice nativo C/C++ nel nostro file sorgente Java, dobbiamo prima dichiarare la chiamata JNI e caricare la libreria nativa, come evidenziato nel riquadro giallo della schermata seguente.

Come mostra la dichiarazione, la chiamata nativa restituisce una stringa Java che possiamo usare ovunque nel nostro file sorgente Java. Come illustrato nella schermata precedente, abbiamo modificato TextView in modo che visualizzi la stringa ottenuta dalla chiamata nativa. Questa operazione è evidenziata nel riquadro rosso.

Questo è un caso molto semplice per dichiarare e usare le chiamate JNI native nei file sorgente Java delle applicazioni Android. Useremo quindi lo strumento “javah” per generare gli stub dell'header JNI per il codice nativo e aggiungere o modificare il codice nativo in modo che sia conforme con le header JNI native.

3. Usare “javah” per generare gli stub dell'header JNI per il codice nativo

Dobbiamo ora modificare il nostro codice nativo in modo che sia conforme alla specifica della chiamata JNI. Anche “javah” ci aiuta a generare automaticamente gli stub appropriati dell'header JNI in base ai file sorgente Java. Per generare le header lo strumento “javah” richiede file di classe Java compilati. Usiamo così lo strumento “ant” per generare rapidamente file di classe Java, come mostrato nella schermata sottostante (“ant debug”).

Usare “javah” per generare l'header jni come mostrato nella schermata (secondo riquadro giallo). Questa operazione creerà la directory “jni” e lo stub dell'header in base alla classe Java. La schermata seguente mostra lo stub dell'header nativa JNI generato.

Creare il corrispondente file sorgente C (“com_example_cpuid_CPUIdApp.c”) per l'header precedentemente generata. Qui di seguito è mostrato il listato del file sorgente:

Chiamiamo il codice nativo cpuid_parse e restituiamo il buffer analizzato come stringa JNI. Siamo ora pronti a compilare il codice nativo usando gli strumenti dell'NDK x86.

4. Compilare il codice nativo con l'NDK per x86

Per ulteriori informazioni sull'installazione e l'utilizzo dell'NDK per l'architettura Intel, si prega di fare riferimento alla sezione della comunità Android (http://software.intel.com/it-it/android/articles/android-ndk-for-intel-architecture) nel sito Web di Intel.

Gli strumenti dell'Android NDK usano un sistema di compilazione che, per compilare il codice nativo, richiede che nella cartella “jni” del progetto sia presente uno specifico file make Android personalizzato, “Android.mk”. Android.mk specifica tutti i file sorgente C/C++ nativi che devono essere compilati, le header e il tipo di compilazione (es. shared_library).

Qui di seguito è mostrato il listato make Android del nostro progetto (“jni/Android.mk”)

Questo è un semplice scenario con due file sorgente C in cui si specifica di compilare una libreria condivisa.

Possiamo ora inviare l'istruzione “ndk-build APP_ABI=x86” per compilare il codice nativo e generare la libreria condivisa. Il sistema di compilazione Android offre un file make supplementare, “Application.mk”, che possiamo usare per specificare ulteriori opzioni di configurazione. Se ad esempio specifichiamo nel file Application.mk tutte le architetture ABI supportate, ndk-build genererà le librerie condivise native destinate a tutte le architetture.

La schermata precedente mostra la compilazione riuscita del codice nativo per x86 e mostra anche la libreria condivisa che viene generata e installata. Siamo ora pronti a ricompilare la nostra applicazione Android da installare/eseguire sull'emulatore x86 o sul dispositivo di destinazione.

5. Ricompilare, installare ed eseguire l'applicazione Android NDK per l'architettura Intel

Possiamo usare “ant debug clean” per rimuovere i vecchi file di compilazione e inviare di nuovo il comando “ant debug” per avviare la compilazione completa del progetto Android. Usare “adb” per reinstallare l'applicazione sul dispositivo di destinazione o nell'emulatore x86, come mostrato nella schermata seguente.

La schermata seguente mostra l'icona dell'applicazione dentro l'emulatore x86 e il risultato dell'esecuzione dell'applicazione nell'emulatore x86.

Abbiamo creato correttamente, dall'inizio alla fine, un'applicazione Android basata su NDK.

Uso degli strumenti dell'NDK x86 per eseguire il porting verso dispositivi basati sull'architettura Intel di applicazioni NDK esistenti

Le applicazioni Android con codice nativo hanno in genere una struttura di progetto standard, con la cartella “jni” che contiene i file sorgente nativi e i corrispondenti file di compilazione Android.mk/Application.mk. Nella sezione precedente abbiamo visto un semplice esempio con codice sorgente nativo e il corrispondente file Android.mk.

Gli strumenti dell'Android NDK ci permettono di specificare in una volta sola tutte le architetture ABI di destinazione nel file Application.mk e generare automaticamente le librerie condivise native per tutte le destinazioni. Il sistema di compilazione Android inserirà automaticamente tutte le librerie native di destinazione all'interno del pacchetto APK e, al momento dell'installazione, il gestore dei pacchetti Android installerà solo la libreria nativa appropriata per l'architettura di destinazione.

Si può richiamare “ndk-build” oppure nel file Application.mk specificare

APP_ABI := all

OPPURE

APP_ABI := armeabi armeabi-v7a x86

Per ulteriori informazioni, fare riferimento a http://developer.android.com/sdk/ndk/index.html.

Per quanto riguarda il porting di un'applicazione Android esistente con codice nativo e che attualmente non è destinata all'architettura x86, il processo per modificare l'applicazione affinché supporti l'architettura Intel è semplice nella maggior parte dei casi (come descritto in precedenza), a meno che l'applicazione non usi costrutti o un linguaggio assembly specifici dell'architettura. Potrebbero anche incidere altri fattori, come l'allineamento della memoria o l'utilizzo di istruzioni specifiche della piattaforma. Per maggiori informazioni, fare riferimento a http://software.intel.com/it-it/android/articles/ndk-android-application-porting-methodologies.

Riepilogo

Questo articolo tratta della creazione e del porting di applicazioni Android basate su NDK per destinarle all'architettura Intel. Con una descrizione dettagliata della procedura abbiamo dimostrato il processo per creare dall'inizio alla fine un'applicazione basata sull'NDK che usi l'architettura Intel. Abbiamo anche descritto un semplice processo, reso disponibile dagli strumenti dell'NDK, per eseguire il porting di applicazioni Android basate su NDK esistenti per destinarle all'architettura Intel.

Avvisi

Intel è un marchio di Intel Corporation registrato negli Stati Uniti e in altri paesi

LE INFORMAZIONI CONTENUTE IN QUESTO DOCUMENTO SONO FORNITE IN ABBINAMENTO AI PRODOTTI INTEL. QUESTO DOCUMENTO NON CONCEDE ALCUNA LICENZA, IMPLICITA O ESPLICITA, MEDIANTE PRECLUSIONE O ALTRO, PER QUANTO RIGUARDA I DIRITTI DI PROPRIETÀ INTELLETTUALE. AD ECCEZIONE DI QUANTO STABILITO DAI TERMINI E DALLE CONDIZIONI DI VENDITA INTEL PER I PRODOTTI IN QUESTIONE, INTEL NON SI ASSUME ALCUNA RESPONSABILITÀ E DISCONOSCE QUALSIASI GARANZIA ESPRESSA O IMPLICITA RELATIVA ALLA VENDITA E/O ALL'UTILIZZO DI PRODOTTI INTEL, INCLUSA LA RESPONSABILITÀ O L'IDONEITÀ AD UNO SCOPO PARTICOLARE, LA COMMERCIABILITÀ O LA VIOLAZIONE DI BREVETTI, COPYRIGHT O ALTRI DIRITTI DI PROPRIETÀ INTELLETTUALE.

Una "Applicazione mission critical"è qualsiasi applicazione in cui i difetti del prodotto Intel potrebbero causare, direttamente o indirettamente, lesioni personali o decesso. QUALORA SI ACQUISTASSERO O UTILIZZASSERO PRODOTTI INTEL PER QUALSIASI APPLICAZIONE MISSION CRITICAL, È NECESSARIO INDENNIZZARE E SOLLEVARE INTEL E LE SUE SOCIETÀ CONTROLLATE, SUBAPPALTATORI E AFFILIATI E I RESPONSABILI, FUNZIONARI E DIPENDENTI DI CIASCUNA DI QUESTE ENTITÀ, DA QUALSIASI RESPONSABILITÀ PER EVENTUALI COSTI PER RECLAMI, DANNI, SPESE E SPESE LEGALI RAGIONEVOLI DERIVANTI, DIRETTAMENTE O INDIRETTAMENTE, DA QUALSIASI RESPONSABILITÀ DEL PRODOTTO, LESIONE PERSONALE O DECESSO CAUSATI IN QUALSIASI MODO DA TALE APPLICAZIONE MISSION CRITICAL, INDIPENDENTEMENTE DAL FATTO CHE INTEL O IL PROPRIO SUBAPPALTATORE ABBIA AGITO IN MODO NEGLIGENTE NELLA PROGETTAZIONE, FABBRICAZIONE O AVVERTENZE DEL PRODOTTO INTEL O DI QUALSIASI SUO COMPONENTE.

Intel può apportare modifiche alle specifiche e alle descrizioni dei prodotti in qualsiasi momento e senza preavviso. I progettisti non devono fare affidamento sull'assenza o sulle caratteristiche di qualunque funzione o sulle istruzioni contrassegnate come "riservate" o "non definite". Intel si riserva di definirle in futuro e non accetta alcuna responsabilità in caso di conflitti o incompatibilità derivanti da ogni loro modifica futura. Le informazioni sono soggette a modifica senza preavviso. Non finalizzare un progetto con queste informazioni.

I prodotti descritti in questo documento possono contenere errori o difetti di progettazione noti come "errata" che possono determinare l'errato funzionamento del prodotto, a differenza di quanto stabilito nelle relative specifiche pubblicate. Gli "errata" attualmente riconosciuti sono disponibili su richiesta.

Per ottenere le specifiche più recenti e prima di inoltrare l'ordine di prodotti, contattare l'ufficio vendite Intel di zona oppure il distributore di fiducia.

Le copie dei documenti con numero d'ordine citati in questo documento, o altra letteratura Intel, possono essere richieste telefonando al numero (USA) 1-800-548-4725 oppure visitando il sito: http://www.intel.com/design/literature.htm * Altri marchi e denominazioni potrebbero essere proprietà di terzi.

Copyright© 2012 Intel Corporation. Tutti i diritti riservati

Serie di training sullo sviluppo per i dispositivi Android* basati su Intel

$
0
0

Questa serie di video presenta una panoramica sui tool di Intel che sono a disposizione degli sviluppatori di Android* tramite Intel® Software. Avrete modo di scoprire i benefici che questi tool offrono alle vostre attività quotidiane di programmatore, dirette o meno a dispositivi Intel. Sono strumenti che miglioreranno la vostra vita di sviluppatore, facendovi risparmiare tempo, consentendovi di creare esperienze migliori e applicazioni per più piattaforme e più architetture. Date un'occhiata ai cinque video di training e seguite i link per saperne di più su ogni tool.

Tool Intel per sviluppatori Android*

Xavier Hallade, ingegnere tecnico e GDE di Intel

Gli sviluppatori Android* possono trarre vantaggio dai tool che offre Intel. Xavier fornisce una rapida panoramica su alcuni tool disponibili, descrive cosa possono fare per voi e i benefici che potete ottenere in termini di produttività e risultati. Tratta anche di come questi tool possono aiutarvi nel debug, nell'ottimizzazione delle prestazioni, nello sviluppo multipiattaforma e altro ancora.

NDK: alla scoperta dell'Android Native Development Kit

Xavier Hallade, ingegnere tecnico e GDE di Intel

Xavier presenta l'Android* Native Development Kit (NDK), il componente ufficiale che potete utilizzare per integrare C/C++ nelle applicazioni Android*. In alcuni casi, l'uso dell'NDK è in grado di generare un notevole incremento nelle prestazioni della vostra applicazione.

Intel® Graphics Performance Analyzers 

Seth Schneider, ingegnere tecnico di Intel

Seth presenta i Graphics Performance Analyzers, un insieme di potenti strumenti che consentono agli sviluppatori di utilizzare completamente il potenziale di prestazioni della piattaforma. Gli analizzatori visualizzano le prestazioni del sistema in tempo reale, rintracciano gli errori, individuano i problemi grafici e altro ancora.

Creare applicazioni native per più sistemi operativi con Intel® INDE​

Karthiyayini Chinnaswamy, ingegnere tecnico di Intel, e Jeff Kataoka, direttore marketing di Intel

Karthi e Jeff descrivono Intel INDE, una suite di produttività per sviluppatori che consente lo sviluppo di applicazioni mobili native per più sistemi operativi e più architetture utilizzando Java* e C++. Date un'occhiata alla serie di tool che vi permetterà di migliorare le prestazioni delle applicazioni e vi farà risparmiare tempo attraverso il riutilizzo del codice e l'accesso semplificato alle funzionalità della piattaforma.

Sviluppare applicazioni in HTML5 utilizzando Intel® XDK

Dale Schouten, ingegnere tecnico consulente di Intel

Intel XDK permette di sviluppare in HTML5 e ottenere applicazioni mobile installabili per Android*, Windows* e iOS*. Dale mostra le caratteristiche del tool che rende facile per gli sviluppatori creare, eseguire il debug e distribuire applicazioni su più sistemi operativi, utilizzando una sola base di codice.

Come impostare le librerie FMOD*, Cocos2D-x*, e OpenAL* per Android* su architettura Intel®

$
0
0

Scarica documento

In precedenza, abbiamo visto le istruzioni su come compilare una libreria FFmpeg su architettura x86. La guida passo dopo passo spiega il processo di configurazione e compilazione di librerie diverse che sono utilizzate in giochi e file multimediali specificatamente per piattaforme x86. Vedremo la configura di FMOD*, Cocos2D-x*, and OpenAL*.

Configurazione e prerequisiti:

Prima di iniziare, ci occorre soddisfare alcuni prerequisiti di download.

  1. Scarica Android ADT Bundle
  2. Scarica NDK
  3. Scarica e installa Cygwin*: Quando vengono richiesti i pacchetti selezionati, cercare i seguenti pacchetti e installarli:

    Autoconf, Automake, binutils, gcc-core, gcc-g++, gcc4-core, gcc4-g++, gdb, pcre, pcre-devel,
    gawk, make, python

    NOTA: Selezionare anche la versione dell’interfaccia grafica utente di make, o non sarà possibile realizzare il progetto tramite NDK.

  4. Scarica JDK
  5. Scaricare Apache Ant

Ora occorre modificare alcune variabili ambientali.

  1. Impostare JAVA_HOME = il percorso in cui è installato il JDK Java*, per me è: C:\Program Files\Java\jdk1.7.0_45
  2. Impostare ANDROID_SDK_ROOT = il percorso completo della cartella SDK. Ad esempio: nel mio caso, ho scaricato ed estratto il bundle ADT in D:\android\, quindi il mio percorso è: D:\android\adt-bundle-windows-x86-20131030\sdk
  3. Impostare NDK_ROOT = il percorso completo della cartella NDK, il mio percorso è: D:\android\android-ndk-r9b
  4. Impostare NDK_ROOT = il percorso completo della cartella NDK, il mio percorso è: D:\android\android-ndk-r9b
  5. Aggiornare la variabile Path per contenere il seguente path = nella cartella JDK, NDK, cartella JDK bin, cartella Cygwin bin, cartella ANT bin, cartella strumenti SDK e cartella piattaforma-strumenti SDK, ciascuna separata da un punto e virgola (;). Ad esempio, nel mio caso, aggiungerò quanto segue:

    D:\cygwin64\bin;C:\Program Files\Java\jdk1.7.0_40\bin;D:\android\adt-bundle-windows-x86_64-20131030\sdk\tools;D:\android\adt-bundle-windows-x86_64-20131030\sdk\platform-tools;%JAVA_HOME%\bin;%ANT_HOME%\bin

 

NOTA: Non terminare le variabili con \ oppure ` oppure altri caratteri speciali.

 

FMOD

FMOD è una libreria commerciale per gestire l’audio. FMOD comprende un set di strumenti per la creazione di contenuti audio che riproduce file musicali di diversi formati su molti sistemi operativi diversi usati in giochi e applicazioni software per fornire funzionalità audio. Di seguito è presente una guida passo dopo passo per integrare la libreria FMOD in un’applicazione Andoid con l’aiuto dell’IDE Eclipse* specificatamente per una piattaforma x86.

Scarica FMOD. Scaricare la versione Android dell’API di FMOD Ex Programmer, come mostrato di seguito:

Per installare FMOD, estrarre «fmodapi44429android.tar.gz» tramite strumenti quali 7-zip in una cartella a scelta.

Costruzione tramite Android NDK:

Per implementare il sonoro tramite l’API FMOD Ex, occorre includerlo come programma C/C++ nel codice e referenziarlo attraverso jni nell’applicazione Android.

FMOD è dotato di librerie C/C++ richiamabili via JNI o linkabili al componente C/C++ dell’applicazione:

  • libfmodex.so per sviluppo generico.
  • libfmodexL.so per la stessa libreria, ma con debug logging che può consentire di determinare qualsiasi problema se necessario.

Le librerie FMOD sono attualmente fornite per la built armeabi e armeabi-v7a ABI per android-3 e la built ABI x86 per android-9.

  • {$FMOD INSTALLED PATH}\api\lib\$(ABI)

L’interfaccia audio completamente nativa OpenSL è il metodo di riproduzione predefinito per i dispositivi che lo supportano (android-9) e non necessita di file aggiuntivi. Per i dispositivi senza supporto OpenSL occorre utilizzare la modalità di uscita Audio Track, che necessita di un file jar FMOD. Questo file jar deve essere aggiunto all’applicazione Java per inizializzare e far funzionare l’uscita audio FMOD:

  • fmodex.jar

Ciò verrà discusso nel prossimo argomento.

NOTA: Dato che l’applicazione di esempio usata qui fa parte della libreria, non abbiamo incluso il codice per l’esempio; invece nel documento sono indicate solo le modifiche necessarie.

Inizializzazione Java

Per attivare l’uscita audio attraverso la modalità di uscita Audio Track occorre includere e inizializzare il driver audio Java FMOD nell’applicazione (non necessario se si usa la modalità di uscita OpenSL). Per fare ciò occorre garantire che fmodex.jar sia referenziato nel progetto Java e che si abbia importato il pacchetto org.fmod.FMODAudioDevice. Il driver audio Java FMOD richiede inoltre che l’applicazione carichi la libreria fmodex.

La classe FMODAudioDeviceè dotata di due funzioni che occorre richiamare per riprodurre l’audio. Sono richiamabili in qualsiasi momento, ma consigliamo di inserire le chiamate di funzione start() e stop() negli override onStart() e onStop() di Activity.

Costruzione di un programma di esempio per Android sulla piattaforma x86

Il processo di compilazione di un programma è lo stesso di quello tramite NDK. Diamo uno sguardo ad un esempio per dimostrarlo. Per questo esempio, useremo il programma di esempio situato nella cartella:

  • {$FMOD INSTALLED PATH}\examples\playsound

Lo chiameremo {$PROJECT DIRECTORY}. Ma prima di svilupparlo tramite NDK, occorre eseguire alcune modifiche:

  1. Accedere alla cartella {$PROJECT DIRECTORY}\jni e aprire il file Application.mk.
  2. Modificare il seguente codice:

    APP_ABI := armeabi armeabi-v7a
    to
    APP_ABI := x86

Poi aprire Cygwin ed eseguire le seguenti attività per realizzare l’applicazione:

ndk-build

  1. Aggiornare la variabile PATH in cygwin come segue:

    export PATH=.:/cygdrive/{$PATH TO NDK}:$PATH

  2. cambiare cartella al percorso del progetto:

    cd /cygdrive/{$PROJECT DIRECTORY}

  3. Eseguire il comando:
  4. Questo realizzerà il progetto e lo renderà pronto all’implementazione.

NOTA: In questo caso sotitutuire tutti i caratteri «\» dal formato di percorso Windows* al carattere «/» per il formato di percorso basato su GNU.

Alla fine di una build corretta, vedrete il seguente messaggio in Cygwin:

[x86] Prebuilt: libfmodex.so <= jni/../../../api/lib/x86/
[x86] Install: libfmodex.so => libs/x86/libfmodex.so
[x86] Cygwin: Generating dependency file converter script
[x86] Compile: main <= main.c
[x86] SharedLibrary: libmain.so
[x86] Install: libmain.so => libs/x86/libmain.so

Ora che il progetto è realizzato è eseguibile tramite l’IDE Eclipse.

Esecuzione dell’applicazione tramite IDE Eclipse

Per avviare l’applicazione da IDE Eclipse, seguire questi passaggi:

  1. Avviare Eclipse e fare clic su File > Import:

  2. Scegliere l’opzione Existing Android... e fare clic su Next:

  3. Sfogliare la directory principale del progetto, es. {$PROJECT DIRECTORY}, quindi accertarsi che l’opzione Copy projects... sia deselezionata e fare clic su Finish:

  4. Comparirà un segno esclamativo rosso sul progetto importato nella scheda package explore come mostrato di seguito:

  5. Per risolvere, fare clic su Window > Preferences come mostrato nella pagina precedente e comparirà la seguente finestra:

  6. Fare clic sull’opzone New... e comparirà quanto segue:

  7. Al posto del campo «Name», digitare:

    FMOD_LIB

  8. Quindi fare clic su File e sfogliare per trovare il seguente file:

    {$FMOD INSTALLED PATH}/api/lib/fmodex.jar

  9. Fare clic su OK.
  10. Quindi fare di nuovo clic su OK e comparirà la seguente finestra; fare clic su Sì:

  11. Verrà risolto l’errore relativo al punto esclamativo rosso.
  12. Quindi fare clic su Project > Properties.

  13. Poi selezionare C/C++ Build > Environment > Add:

  14. Digitare ANDROID_NDK_ROOT nel campo Name e il percorso completo alla cartella installata nel campo Value. Fare clic su OK:

  15. Quindi fare clic su Apply e poi OK:

Ora se si vuole avviare l’applicazione ma solo dopo aver copiato tutti i file dai due set di multimedia di esempio:

{$FMOD INSTALLED PATH}\examples\media\* and
{$FMOD INSTALLED PATH}\fmoddesignerapi\examples\media\*

Su una cartella chiamata fmod nella root della scheda SD.

NOTA: L’applicazione potrebbe non avviarsi nel simulatore.

Impostazioni specifiche per piattaforma x86

È essenziale quando si realizza un’applicazione specifica per piattaforma x86 che si eseguano le seguenti modifiche: (Queste modifiche erano state incorporate come parte della procedura della realizzazione del progetto.)

  1. Accedere alla cartella {$PROJECT DIRECTORY}\jni e aprire il file Application.mk (crearne uno se non presente).
  2. Modificare il seguente codice:

    APP_ABI := armeabi armeabi-v7a
    to
    APP_ABI := x86

Output della build

L’output della build sarà situato in {$PROJECT DIRECTORY} nel modo seguente:

Le librerie generate, libmain.so e libfmodex.so, saranno presenti nella cartella {$PROJECT DIRECTORY}\libs\x86.

Gli oggetti generati saranno nella cartella {$PROJECT DIRECTORY}\obj.

Errori e problemi noti

Sono presenti errori durante la realizzazione tramite NDK, quindi impostare i permessi di accesso a «Controllo completo» per «Tutti».

Inoltre tenere a mente che l’applicazione potrebbe non avviarsi nell’emulatore e che sarà possibile avviarla sul dispositivo solo dopo aver copiato tutti i file dai due set di file multimediali di esempio:

{$FMOD INSTALLED PATH}\examples\media\* and
{$FMOD INSTALLED PATH}\fmoddesignerapi\examples\media\*

Su una cartella chiamata fmod nella root della scheda SD.

Cocos2D-x:

Allora adesso vediamo il processo di realizzazione di un’applicazione Android multipiattaforma con l’aiuto del motore di gioco Cocos2d-x specifico per la piattaforma x86.

Il programma di esempio utilizzato in questo documento per spiegare il processo fa parte del Cocos2d-x Game Engine e si trova nella cartella \samples\Cpp\ dentro la cartella cocos2d-x-2.1.1.

Cocos2d-Xè una porta multipiattaforma scritta in C++ utilizzabile con iOS*, Android, Windows, Marmalade, Linux*, Bada, e BlackBerry* 10. Questa porta è dotata di Lua* e JavaScript* come script binding. È possibile leggere la documentazione di supporto di Cocos2d-X sul loro sito.

Prima di utilizzare Cocos2d-x, accertarsi di soddisfare i prerequisiti come dettagliato in precddenza nella sezione Prerequisiti.

Scaricare Cocos2d-x:

Scaricare Cocos2d-x e scegliere la versione più recente. Inoltre ricordarsi di scegliere l’opzione Cocos2d-x semplice e non l’opzione -html5.

Passaggi per installare e configurare Cocos2d-x:

  1. Estrarre il file zip scaricato nel passaggio precedente sull’unità C:\ Drive. Ho estrtto il mio su D:\Cocos2d-x.
  2. Devono essere presenti due cartelle nella cartella Cocos2d-x. Per me sono: D:\Cocos2d-x\__MACOSX e D:\Cocos2d-x\cocos2d-x-2.2.1.
  3. Impostare le variabili ambientali per Cocos2d-x come mostrato di seguito:

    COCOS2DX_ROOT = il percorso completo nella cartella cocos2d-x-2.2.1, nel mio caso è: D:\Cocos2d-x\cocos2d-x-2.2.1

Prima di cominciare, rendere note alcune variabili in quanto saranno usate in modo estensivo attraverso:

  • {$ADT PATH} = il percorso completo nel bundle ADT Android, nel mio caso è: D:\android\adt-bundle-windows-x86_64-20131030
  • {$ECLIPSE PATH} = il percorso completo a eclipse fornito con il bundle ADT, per me è: {$ADT PATH}\eclipse
  • {$COCOS2D-X PATH} = il percorso completo alla cartella cocos2d-x-2.2.1, nel mio caso è: D:\Cocos2d-x\cocos2d-x-2.2.1
  • {$WORKSPACE PATH} = il percorso completo allo spazio di lavoro Android Eclipse, nel mio caso è: D:\and_proj_coco

Configurazione di un progetto Cocos2d-x in IDE Eclipse:

  1. Eseguire Eclipse dal seguente percorso: {$ECLIPSE PATH}\eclipse.exe
  2. Creare il workspace quando richiesto. Ho creato il mio in {$WORKSPACE PATH}, come mostrato sotto:

  3. Fare clic su File > Import come mostrato di seguito:

  4. Comparirà una finestra come quella mostrata di seguito:

  5. Espandere la sezione Android. Quindi fare clic sull’opzione Existing Android Code Into Workspace e fare clic su Avanti, come mostrato sopra.
  6. Fare clic su Browse... come mostrato sotto:

  7. Andare a {$COCOS2D-X PATH}\samples\Cpp\HelloCpp\proj.android come mostrato di seguito e fare clic su OK: :

  8. Per questo progetto di esempio, prima di fare clic su Fine, accertarsi di NON SELEZIONARE i progetti Copy nell’opzione workspace:

  9. Dopo aver importato, Eclipse potrebbe visualizzare alcuni errori. Per ora ignorarli e procedere ai seguenti passaggi.

    NOTA: In futuro, se non si vuole utilizzare il codice di progetto originale e si è sicuri che importare il codice di progetto nel workspace non influirà sull’esecuzione del codice, allora selezionare l’opzione cerchiata sopra

     

  10. Poi ripetere i passaggi c – h con la differenza che invece di importare {$COCOS2D-X PATH}\samples\Cpp\HelloCpp\proj.android, verrà importato: {$COCOS2D-X PATH}\cocos2dx\platform\android come mostrato più sotto, è possibile selezionare il progetto Copy nell’opzione workspace se si desidera:

  11. Se gli errori trovati al passaggio h non sono risolti a questo punto, procedere al seguente passaggio come segue.
  12. Ora, nella scheda Package Explorer a sinistra, fare clic destro su libcocos2dx e fare clic su Properties, come mostrato di seguito:

  13. Nella finestra che apparirà, fare clic sull’opzione Android nella scheda a sinistra e accertarsi che l’opzione Is Library sia selezionata, come mostrato sotto, quindi fare clic su Apply e finalmente su OK.

  14. Analogamente, aprire la finestra Properties per il progetto HelloCpp seguendo i passaggi j – k per il profetto HelloCpp. Apparirà la finestra come mostrato di seguito:

  15. Rimuovere qualsiasi cosa dalla sezione Library contrassegnata con una croce rossa e fare clic su Add.
  16. Scegliere libcocos2dx e fare clic su OK come mostrato di seguito:

  17. Ora è possibile vedere che la sezione Library è popolata da un contrassegno di spunta verde come mostrato sotto, quindi fare clic su Apply e OK:

  18. A questo punto, Eclipse ricostruirà il progetto. Se tutti gli errori sono risolti allora ignorare questo passaggio. In caso contrario, allora eliminare il progetto HelloCpp esistente dalla scheda Package Explorer e accertarsi che mentre si elimina NON si scelga di rimuovere dal disco, in quanto NON È POSSIBILE ANNULLARE L’OPERAZIONE, ed eseguire di nuovo i passaggi c – h e i passaggi m – p:

  19. Ora, il progetto dovrebbe risultare come questo:

Congratulazioni! Avete aperto correttamente il vostro progetto in IDE Eclipse. Ora continuiamo costruendo il vostro progetto.

Costruzione di un progetto Cocos2d-x in IDE Eclipse:

  1. Dalla scheda Package Explorer, accedere a HelloCpp > jni > Application.mk come mostrato di seguito:

  2. Aggiungere la seguente stringa alla build per la piattaforma x86:

    APP_ABI := x86

  3. Ora, dalla scheda Project nella barra menu superiore, prima fare clic su Clean, quindi Build Project, come mostrato di seguito:

Apertura e costruzione di un progetto Cocos2d-x tramite Cygwin:

  1. Eseguire Cygwin e accedere alla cartella del progetto di esempio HelloCpp tramite il seguente comando:

    cd /cygdrive/d/Cocos2d-x/cocos2d-x-2.2.1/samples/Cpp/HelloCpp/proj.android

    Il percorso dipende da {$COCOS2D-X PATH}.

  2. Accertarsi che la seguente stringa sia aggiunta al file Application.mk presente nella cartella /jni:

    APP_ABI := x86

  3. Per costruire il progetto, mentre si è nella cartella /proj.android, inserire il comando:

    ./build_native.sh

NOTA: Se si verifica un errore, accertarsi che:

  • I pacchetti necessari per Cygwin siano stati scaricati correttamente.
  • La variabile PATH di Cigwin contenga i percorsi alle cartelle Android NDK, SDK, JDK, e COCOS2D-X come menzionato nella sezione Prerequisiti.

Una volta che si segue e completa la procedura di costruzione, i binari sono generati nella seguente cartella:

proj.android\obj\local\x86

Ad esempio:

proj.android\obj\local\x86\libhellocpp.so
proj.android\obj\local\x86\libcocos2d.a

OpenAL (Open Audio Library)

OpenAL (Open Audio Library) è un’interfaccia di programmazione di applicazioni audio multipiattaforma (API). È progettata per un efficace rendering di multicanali e audio posizionale tridimensionale. Il suo stile e convenzione API assomigliano deliberatamente a quelli di OpenGL. Fin dalla versione 1.1, Creative ha fatto la sua implementazione proprietaria. Tuttavia, OpenAL-Softè ampiamente utilizzato come alternativa open source. Utilizzeremo una versione di OpenAL-Soft adottata soprattutto per Android.

Prima di iniziare a lavorare su OpenAL, scaricare quanto richiesto dalla sezione Prerequisiti.

Scaricare una sorgente aggiornata all’ultima versione di patch di OpenAL:

Per lavorare con OpenAL, occorre una sorgente aggiornata all’ultima versione di patch adattata specialmente per Android.

Grazie a Martins Mozeiko e Chris Robinson esiste una versione di OpenAL che è stata adattata alla piattaforma Android. Scaricare la versione più recente del codice sorgente OpenAL aggiornato all’ultima versione di patch.

Alternativamente, è possibile scaricare questa sorgente tramite il terminale Cygwin:

  1. Eseguire Cygwin e inserire il seguente comando:

    git clone http://repo.or.cz/r/openal-soft/android.git OpenAL

  2. La repository sarà clonata in una cartella chiamata OpenAL in pwd, per me è: /home/user001 or ~.

NOTA: Nel caso della versione Windows di Cygwin, la cartella /home si trova nella directory dove è installato Cygwin. Nel mio caso è: D:\cygwin64

Come configurare la piattaforma x86:

Prima di iniziare a costruire, creare un normale progetto Android OpenAL Hello. Lasciare il percorso per la cartella del progetto {$PROJECT_DIR}, come: D:\openal_proj\HelloOpenAL.

Per compilare tramite OpenAL per Android, seguire questi passaggi:

  1. Per compilare OpenAL occorre un file chiamato config.h. Copiarlo da

    {$OPENAL_DIR}/android/jni
    To
    {$OPENAL_DIR}/include

    NOTA: Qui, {$OPENAL_DIR}è il percorso completo per la directory OpenAL scaricata nel passaggio precedente. Per me è: ~/openal

  2. Dopo aver effettuato la modifica, copiare questa cartella OpenAL nella cartella del progetto {$PROJECT_DIR}.
  3. Aggiungere l’interfaccia nativa al progetto nei passaggi seguenti.
  4. Ho usato il file org_pielot_helloopenal_HelloOpenAL.c per implementare i metodi di riproduzione audio dall’interfaccia nativa.
  5. Quindi occorre creare due file make, Android.mk e Application.mk e inserirli nella cartella jni insieme con la cartella .c e il suo file intestazione personalizzato .h.

    NOTA: Il dettaglio di questi file e la loro sistemazione vengono forniti al termine del documento.

Per configurare il progetto specificatamente per x86, accertarsi che i seguenti file siano modificati per contenere i rispettivi valori dati:

Application.mk

APP_OPTIM := release
APP_ABI := x86

Come realizzare il progetto:

  1. Aprire Cygwin e accedere a {$PROJECT_DIR}:

    cd /cygdrive/{$PROJECT_DIR}

    dove {$PROJECT_DIR}è il percorso completo alla directory del profetto. Nel mio caso è:

    cd /cygdrive/d/openal_proj

  2. Esegire il seguente comando per includere il percorso nella cartella NDK nella variabile ambientale PATH di Cygwin:

    export PATH=.:/cygdrive/{$PATH TO NDK}:$PATH

    Ad esempio, nel mio caso:

    export PATH=.:/cygdrive/d/android/android-ndk-r9b:$PATH

  3. Eseguire il comando:

    ndk-build

    Questo costruirà il progetto OpenAL per l’architettura x86.

Output della build:

L’output della build sarà situato in {$PROJECT_DIR}:

Le librerie generate, libopenal.so e libopenaltest.so, saranno presenti nella cartella {$PROJECT _DIR}\libs\x86.

Gli oggetti generati saranno nella cartella {$PROJECT_DIR}\obj.

Librerie OpenSSL*:

Il seguente processo descrive come realizzare le librerie OpenSSL per Android su x86.

Prerequisiti

  1. Un PC host con Windows 7 o successivo.
  2. Dato che le librerie OpenSSL sono state sviluppate in linguaggio C nativo, il requisito primario per la compilazione è Android NDK, che ha il supporto integrato per compilare librerie per più piattaforme per specifiche architetture (ARM, x86, ecc.).

La sorgente OpenSSL Android è scaricabile sia da eighthave project che da guardian project su github.

Costruzione per x86:

Le impostazioni multipiattaforma sono realizzabili come per ogni altra applicazione Android tramite le impostazioni Application Binary Interface.

La seguente stringa deve essere aggiunta al file jni/Application.mk per realizzare le librerie per l’architettura x86.

APP_ABI := x86

Una volta installato NDK e scaricato OpenSSL Android e scompattato in un disco locale (ad esempio C:\openssl-android-master), seguire le istruzioni di seguito per realizzare le librerie per x86:

  1. Aprire il prompt dei comandi (Start->All Programs->Accessories->Command Prompt).
  2. Spostarsi nella cartella Android OpenSSL scaricata e scompattata, ad esempio,
    >cd C:\openssl-android-master.
  3. Assicurarsi di impostare le impostazioni di configurazione necessarie per x86, ad esempio APP_ABI := x86.
  4. Dare il comando NDK build, ad esempio C:\openssl-android-master > ndk-build.

    Ciò costruirà le librerie libssl, libcrypto, openssl.

    Le librerie generate si trovano nella seguente posizione:

    C:\openssl-android-master\libs\x86\libcrypto.so
    C:\openssl-android-master\libs\x86\libssl.so

Informazioni sull’autore

Praveen Kundurthy lavora presso Intel® Software and Services Group. Ha un master in Ingegneria informatica. I suoi interessi principali riguardano le tecnologie mobili, Windows e lo sviluppo di giochi.

Articoli e risorse correlati

Aggiunta del supporto x86 alle app Android* tramite Unity* Game Engine

$
0
0

Panoramica

L’attivazione di giochi esistenti SDK Android* basati su Unity* ARM* con supporto x86 nativo è semplicissimo.  Questo documento vi guiderà passo dopo passo alla realizzazione di fat APK che includano sia le librerie x86 che ARM dall’interno delle versioni più recenti Unity 4 o Unity 5.   

Intel e Unity stanno collaborando per portare la funzionalità Android x86 a una prossima release pubblica di Unity 4.6 e Unity 5. Aggiorneremo https://software.intel.com/it-it/articles/unity quando verrà rilasciata la release. Se si desidera accedere in anticipo o la versione 4.5.4, contattare il proprio account manager Intel.

Aggiunta del supporto x86 nativo Android*

In aggiunta a ARM, Unity ora fornisce agli sviluppatori il supporto x86 nativo. Quando si crea una build Android tramite Unity 4 o Unity 5, questa crea automaticamente una fat APK contenente sia le librerie x86 che ARM.

Best practice: Seguire le pratiche di programmazione Unity per assicurarsi che i progetti siano aggiornati e la versione software di Unity sia la più recente. SDK e NDK Android devono inoltre essere aggiornati per garantire la piena compatibilità.

Fase 1

Con il proprio progetto aperto, fare clic sulle impostazioni File > Build per aprire le impostazioni Build (Figura 1).

Figura 1.Impostazioni della build nel menu a discesa File

Fase 2

All’interno di Build Settings, accertarsi che sia selezionato Android, quindi fare clic su Build (Figura 2)

Figura 2.Build Settings, accertarsi che sia selezionato Android*, quindi fare clic su Build

 

Fase 3

Dopo aver fatto clic su Build, specificare la cartella di salvataggio.

Ecco fatto! L’APK è ora dotata di supporto x86 nativo.

Con l’uso sia del motore di gioco Unity più recente e di SDK e NDK Android, gli sviluppatori hanno il supporto sia per x86 che ARM il tutto in una fat APK. L’APK che ne risulta contiene sia le librerie x86 che ARM e dopo il download il dispositivo selezionerà quale libreria è applicabile al suo tipo di hardware.  Tenere presente che le dimensioni della fat APK aumenteranno di poco a meno che non vengano incluse le informazioni di debug complete.È possibile accertarsi che NON vengano incluse le informazioni di debug complete verificando che non sia selezionato«Development Build» nella sezione di impostazioni della build. 

È disponibile una pagina speciale per gli sviluppatori x86 Unity all’indirizzo www.intel.com/software/unity per ulteriore supporto. 

Sommario

Come appena visto, è facile creare giochi Android per la piattaforma x86 tramite le versioni più recenti di Unity 4 o Unity 5. Il supporto x86 nativo permetterà alle app di ottenere prestazioni migliori e tempi di caricamento più rapidi.

Tutorial: Uso di Intel® INDE GPA per migliorare le prestazioni del vostro gioco Android*

$
0
0

Download PDF

Download Code Sample

Introduzione

Questo tutorial presenta una guida esplicativa per l'analisi di prestazioni, l'identificazione di colli di bottiglia e l'ottimizzazione del rendering di un'applicazione OpenGL ES* 3.0 su Android*. L'applicazione d'esempio, intitolata “City Racer”, simula una corsa su strada attraverso uno scenario urbano stilizzato.  L'analisi delle prestazioni dell'applicazione è fatta usando la suite di strumenti Intel® INDE Graphics Performance Analyzers (Intel® INDE GPA).

 

City Racer Icon
La città combinata e la geometria del veicolo è composta da circa 230.000 poligoni (690.000 vertici) con diversi materiali mappati illuminati da una singola luce direzionale che non proietta ombre.  Il materiale sorgente fornito include codice, file del progetto e materiale artistico necessario per costruire l'applicazione, tra cui ottimizzazioni del codice sorgente identificate attraverso questo tutorial.

 

Riconoscimenti

Questo tutorial è una versione Android e OpenGL ES 3.0 di the Intel Graphics Performance Workshop for 3rd Generation Intel® Core™ Processor (Ivy Bridge) (PDF) creato da David Houlton.  Viene fornito con Intel INDE GPA.

Organizzazione del tutorial

Questo tutorial vi guida attraverso quattro fasi di ottimizzazione successive.  Ad ogni fase l'applicazione viene analizzata con Intel INDE GPA per identificare specifici colli di bottiglia delle prestazioni.  Un'ottimizzazione adeguata viene quindi attivata nell'applicazione per superare il collo di bottiglia e viene analizzata di nuovo per misurare le prestazioni raggiunte.  Le ottimizzazioni applicate sono generalmente in linea con le linee guida fornite dalla Guida per lo sviluppatore per processore grafico Intel® (PDF).

Durante il tutorial, le ottimizzazioni applicate migliorano le prestazioni del rendering di City Racer dell'83%.

Prerequisiti

 

Applicazione d'esempio City Racer

City Racer è diviso logicamente in simulazione di corsa e componenti secondarie di rendering.  La simulazione di corsa include parametri di accelerazione, frenaggio e virata del veicolo e l'intelligenza artificiale per seguire la pista ed evitare le collisioni.  Il codice di simulazione della corsa si trova nei file track.cpp e vehicle.cpp e non viene influenzato da nessuna delle ottimizzazioni applicate da questo tutorial.

Il componente rendering consiste nel disegnare la geometria di veicoli e scenario tramite OpenGL ES 3.0 e il nostro framework CPUT sviluppato internamente.  La versione iniziale del codice di rendering rappresenta un primo sforzo, contenente diverse scelte di progettazione che limitano le prestazioni.

Mesh e texture vengono caricati dal file Media/defaultScene.scene.  Le singole mesh sono contrassegnate come elementi dello scenario preposizionati, scenario di istanza con dati di trasformazione per istanza o veicoli per i quali la simulazione fornisce i dati di trasformazione.  Sono presenti diverse telecamere nella scena:  una segue ciascuna macchina e una telecamera aggiuntiva consente all'utente di esplorare liberamente lo scenario.  Tutte le analisi prestazionali e le ottimizzazioni di codice sono destinate alla modalità telecamera che segue il veicolo.

Per gli scopi di questo tutorial, City Racer è stato progettato per avviarsi in pausa, fattore che consente di percorrere ogni fase di creazione del profilo con impostazioni dati identiche.  È possibile togliere la messa in pausa di City Racer togliendo la spunta alla casella in City Racer HUD o impostando g_Paused = false sopra CityRacer.cpp.

 

Potenziale di ottimizzazione

Considerate l'applicazione City Racer come un prototipo funzionale ma non ottimizzato.  Nel suo stato iniziale fornisce il risultato visivo desiderato, ma non le prestazioni di rendering.  Possiede una serie di scelte tecniche e progettuali che sono rappresentative di quelle che trovereste in un tipico gioco in sviluppo che limita le prestazioni di rendering.  L'obiettivo della fase di ottimizzazione dello sviluppo è identificare i colli di bottiglia prestazionali uno per uno, realizzare modifiche al codice per risolverli e misurare i miglioramenti ottenuti.

Tenete presente che questo tutorial è indirizzato solo a un sottoinsieme ridotto di ottimizzazioni possibili che potrebbero essere applicate a City Racer.  In particolare, considera soltanto le ottimizzazioni applicabili completamente nel codice sorgente, senza alcuna modifica a modello e texture.  Altre ottimizzazioni relative a modifiche delle risorse sono qui escluse semplicemente perché diventano in un certo senso macchinose da implementare in un tutorial, ma possono essere identificate tramite strumenti di Intel INDE GPA e dovrebbero essere considerate in un'ottimizzazione di un gioco reale.

I numeri prestazionali mostrati in questo documento sono acquisiti su un sistema basato su processore Intel® Atom™ (nome in codice Bay Trail) in esecuzione su Android.  I numeri possono variare sul vostro sistema, ma le relazioni prestazionali relative dovrebbero essere simili e condurre logicamente alle stesse ottimizzazioni delle prestazioni.

Le ottimizzazioni da applicare durante il tutorial si trovano in CityRacer.cpp. Possono essere attivate tramite l'HUD di City Racer o tramite modifiche dirette in CityRacer.cpp.

CityRacer.cpp

CityRacer.cpp

bool g_Paused = true;
bool g_EnableFrustumCulling = false;
bool g_EnableBarrierInstancing = false;
bool g_EnableFastClear = false;
bool g_DisableColorBufferClear = false;
bool g_EnableSorting = false;

Si attivano uno ad uno man mano che si procede attraverso le fasi di ottimizzazione.  Ciascuna variabile controlla la sostituzione di uno o più segmenti di codice per raggiungere l'ottimizzazione per quella fase del tutorial.

 

Tutorial per l'ottimizzazione

La prima fase consiste nel costruire e implementare City Racer su un dispositivo Android.  Se il vostro ambiente Android è configurato correttamente, il file buildandroid.bat situato in CityRacer/Game/Code/Android eseguirà queste fasi per voi. 

Successivamente, avviare Intel INDE GPA Monitor, fare clic destro sull'icona del vassoio di sistema e selezionare System Analyzer.

System Analyzer vi mostrerà un elenco di possibili piattaforme alle quali connettersi. Scegliete il vostro dispositivo Android x86 e premete “Connetti”.

System Analyzer - Choose your Android x86 device

Quando System Analyzer si connette al vostro dispositivo Android, visualizzerà un elenco di applicazioni disponibili per il profiling. Scegliete City Racer e attendete che si avvii.

System Analyzer - a list of applications available for profiling

Mentre City Racer è in esecuzione, premere il pulsante di acquisizione frame per acquisire uno snapshot di un frame GPU per l'analisi.

Capture a snapshot of a GPU frame to use for analysis

Esaminate il frame

Aprite Frame Analyzer per OpenGL* e scegliete il frame di City Racer che avete appena acquisito, che vi consentirà di esaminare le prestazioni della GPU in dettaglio.

Open Frame Analyzer for OpenGL* to examine GPU performance

The timeline corresponds to an OpenGL draw call

La timeline in alto è situata in “erg” di lavoro ugualmente distanziati, ciascuno dei quali generalmente corrisponde a una draw call OpenGL.  Per una visualizzazione più tradizionale della timeline, selezionate GPU Duration sugli assi X e Y. In questo modo ci verrà mostrato quali erg stanno consumando più tempo della GPU e dove dovremmo inizialmente concentrare i nostri sforzi.  Se non vengono selezionati erg, allora il pannello sulla destra mostra il nostro tempo della GPU per l'intero frame, che è 55ms.

GPU duration

Ottimizzazione 1 – Frustum Culling

Quando si visualizzano tutte le draw, possiamo vedere che sono presenti molti elementi disegnati che non compaiono visualmente sullo schermo.  Cambiando l'asse Y su Post-Clip Primitives, gli spazi in questa visualizzazione servono a indicare quali draw sono inutili perché la geometria è completamente clippata.

A view-frustum culling routine

Gli edifici in City Racer sono combinati in gruppi secondo le posizioni dello spazio. Possiamo prendere i gruppi non visibili e quindi eliminare il lavoro della GPU associato ad essi. Attivando la casella Frustum Culling, ciascuna draw sarà eseguita tramite una routine di visualizzazione frustum culling sulla CPU prima di essere inviata alla GPU.

Attivate la casella Frustum Culling e utilizzate System Analyzer per acquisire un altro frame.  Una volta acquisito il frame, aprirlo di nuovo in Frame Analyzer.

Frame Analyzer after frustum culling option enabled

Visualizzando questo frame possiamo vedere che il numero di draw si è ridotto del 22% da 740 a 576 e il nostro tempo della GPU totale si è ridotto del 18%.

Frustum Culling Draw calls

Frustum Culling GPU duration

Ottimizzazione 2 – Instancing

Mentre frustum culling ha ridotto la quantità totale di erg, sono sempre presenti un discreto numero di piccoli erg (evidenziati in giallo) che, quando presi cumulativamente, aggiungono una quantità di tempo della GPU non indifferente.

A non-trivial amount of GPU time

Esaminando la geometria per questi erg possiamo vedere che la maggior parte di questi sono le barriere concrete che delineano i lati della pista.

Concrete barriers which line the sides of the track

Possiamo eliminare molte delle aree coinvolte in queste draw combinandole in una singola draw di istanza.  Attivando la casella Barrier Instancing, le barriere saranno combinate in una singola draw di istanza che andrà a rimuovere l'esigenza della GPU di inviarle una per una tramite una draw alla GPU.

Attivate la casella Barrier Instancing e utilizzate System Analyzer per acquisire un altro frame.  Una volta acquisito il frame, aprirlo in Frame Analyzer.

Frame Analyzer - after barrier instancing enabled

Visualizzando questo frame possiamo vedere che il numero di draw si è ridotto del 90% da 576 a 60.

Draw calls before concrete barrier instancing

Draw calls after concrete barrier instancing

Le draw call prima dell'attivazione di barrier instancing (in alto) e dopo l'instancing (in basso)

Inoltre, la durata della GPU si è ridotta del 71% a 13ms.

Instancing gpu duration

Ottimizzazione 3 – Front to Back Sorting

Il termine “overdraw” si riferisce alla scrittura di ciascun pixel più volte; questo può influire sul pixel fill rate e aumentare il tempo di rendering del frame.  Esaminando le misurazioni Samples Written mostrano che ciascun pixel viene scritto circa 1,8 volte per frame (Risoluzione / Samples Written).

Output Merger

Mettendo in ordine le draw front to back prima del rendering è un modo relativamente diretto di ridurre l'overdraw dato che la pipeline della GPU rifiuterà i pixel ostruiti da draw precedenti.

Attivate la casella Sort Front to Back e utilizzate System Analyzer per acquisire un altro frame.  Una volta acquisito il frame, aprirlo in Frame Analyzer.

Frame Analyzer after enabling sort front to back

Visualizzando questo frame possiamo vedere che il numero di Samples Written si è ridotto del 6% e il nostro tempo della GPU totale si è ridotto del 8%.

Output Merger after enabling sort front to back

GPU duration after enabling sort front to back

 

Ottimizzazione 4 – Fast Clear

Un ultimo sguardo ai nostri tempi delle draw mostra il primo erg che occupa il singolo tempo della GPU più lungo.  Selezionando questo erg si scopre che non si tratta di una draw ma di una glClear call.

First erg taking the longest individual GPU time

glClear call

L'hardware della GPU di Intel è dotato di un percorso di ottimizzazione che esegue un “fast clear” in una frazione del tempo che occorre per un clear tradizionale.  Un fast clear è eseguibile impostando glClearColor su tutto nero o tutto bianco (0, 0, 0, 0 o 1, 1, 1, 1).

Attivate la casella Fast Clear e utilizzate System Analyzer per acquisire un altro frame.  Una volta acquisito il frame, aprirlo in Frame Analyzer.

Frame Analyzer after enabling fast clear

Visualizzando questo frame possiamo vedere che la durata della GPU è diminuita dell'87% durante il clear regolare, da 1,2ms a 0,2ms.

GPU duration for the clear decreased

GPU duration for the clear decreased

Come risultato, la durata del frame globale della GPU è diminuita del 24% a 9,2ms.

The overall frame duration of the GPU decreased

 

Conclusione

Questo tutorial ha preso un'applicazione di una prima fase di gioco rappresentativa e utilizzato Intel INDE GPA per analizzare il comportamento dell'applicazione e realizzare modifiche mirate per migliorare le prestazioni.  Le modifiche eseguite e i miglioramenti realizzati sono stati:

OttimizzazionePrimaDopo% Miglioramento
Frustum Culling55.2ms45.0ms82%
Instancing45.0ms13.2ms71%
Sorting13.2ms12.1ms8%
Fast Clear12.1ms9.2ms24%
Overall GPU Optimizations55.2ms9.2ms83%

Il software e i carichi di lavoro utilizzati nei test prestazionali possono essere stati ottimizzati solo per le prestazioni su microprocessori Intel. I test prestazionali, quali SYSmark* e MobileMark*, sono misurati tramite sistemi computazionali, componenti, software, operazioni e funzioni specifici. Qualsiasi modifica a questi fattori può provocare una variazione nei risultati. Dovreste consultare altre informazioni e test prestazionali per assistervi nella valutazione completa degli acquisti, tra cui le prestazioni di un determinato prodotto quando combinato con altri prodotti. Per maggiori informazioni accedere a http://www.intel.com/performance.

In tutto, dall'implementazione iniziale di City Racer alla versione ottimizzata meglio, abbiamo dimostrato un miglioramento delle prestazioni di rendering del 300%, da 11 fps a 44 fps.  Dato che questa implementazione inizia a livello non ottimale, uno sviluppatore che applichi queste tecniche non vedrà probabilmente raggiunte le stesse prestazioni assolute di un videogioco reale.

Nonostante ciò, l'obiettivo principale di questo tutorial non è l'ottimizzazione di questa applicazione d'esempio specifica, ma le prestazioni potenziali raggiunte tramite i consigli della Guida dello sviluppatore per processori grafici Intel e l'utilità di Intel INDE GPA nel trovare e misurare questi miglioramenti.

Costruzione della vostra prima app per Android* e iOS* su Apple* Mac* OS X* tramite Multi-OS Engine

$
0
0

Questo tutorial vi permetterà di realizzare la vostra prima applicazione multipiattaforma usando Multi-OS Engine installato su Mac OSX* a cui ci riferiamo come build locale. Potete inoltre sviluppare le vostre applicazioni Android* e iOS* in Android Studio su Windows* ma per simulare l'applicazione iOS, dovrete implementare via remoto l'app su un sistema Mac che esegue Xcode* (d'ora in poi build remota). In questo caso, verificate la nostra guida introduttiva con Multi-OS Engine (build remota).

In questo tutorial, vi mostrerò come creare una semplice applicazione Hello World per Android e iOS con codice condiviso tra le due applicazioni. In uno scenario realistico, la maggior parte della logica di applicazione sarà condivisa.

Prerequisiti

Per cominciare, occorre rispettare i requisiti minimi di software seguenti:

  1. Android Studio* 1.0 o superiore
  2. Xcode* 6 o superiore
  3. Java* Development Kit 1.7 o superiore
  4. Android SDK

Flusso di lavoro generale

L'iter per creare app per Android e iOS è relativamente semplice.

  1. Per creare un'applicazione iOS in Android Studio, dobbiamo iniziare prima con un progetto Android.
  2. Successivamente creiamo un modulo Multi-OS Engine (che sarà l'applicazione iOS)
  3. Per applicazioni con codice condiviso, creiamo un modulo denominato comune (libreria Java condivisa)
  4. In seguito aggiungiamo il modulo comune come dipendenza per l'applicazione Android e iOS
  5. Infine, configuriamo gli script Gradle*, costruiamo e avviamo le nostre app. 

Creazione delle nostre prime applicazioni Android e iOS con logica condivisa

  1. Create un progetto Android in Android Studio
    Create Android project in Android Studio
  2. Inserite nome dell'applicazione, dominio della società e scegliete una posizione dove salvare il progetto. Una buona pratica è di archiviare i vostri progetti in una cartella chiamata Project sotto il vostro nome utente. Potrete seguire pedissequamente i passaggi descritti qui per essere certi di non incappare in nessun problema. Prestate attenzione al nome del pacchetto generato automaticamente (com.mycompany.myfirstapp) che è in lettere minuscole. Fate clic su Avanti.
    Android Studio project configuration
  3. Configurate il vostro dispositivo di destinazione e le impostazioni del livello API. Se volete cominciare immediatamente, procedete con le impostazioni predefinite facendo clic su Avanti.
  4. Scegliete “Blank Activity” nella finestra Add an activity to Mobile e fate clic su Avanti.
  5. Nella finestra Customize the Activity, è possibile lasciare le impostazioni così come sono. Fate clic su Fine per accettare la configurazione predefinita. 

  6. A questo punto, Android Studio ha creato un progetto Android. Nel pannello del progetto, noterete ilmodulo dell'app. Questo modulo è la vostra applicazione Android. Proseguiamo ora aggiungendo un modulo Multi-OS Engine, che sarà al termine la vostra applicazione iOS.

  7. Nel pannello del progetto, fate clic destro dovunque e scegliete New > Intel Multi-OS Module

  8. Clic sull'applicazione Hello World e clic su Avanti
  9. In questa finestra, creerete un progetto Xcode. Più avanti potrete aprire il progetto iOS creato da Android Studio, in Xcode, soprattutto se volete usare Storyboard Xcode per progettare l'interfaccia utente nativa. Inserite il nome del progetto Xcode (di solito il nome della vostra applicazione), il nome del prodotto (il nome dell'applicazione), i dettagli di organizzazione e l'ID della società.

    In questo esempio, inseriremo i seguenti dettagli che corrispondono a Android S:

    Nome progetto Xcode: myfirstapp
    Nome prodotto: myfirstapp
    Nome organizzazione:
    mycompany
    Identificativo società: com.mycompany


  10. Fare clic su Avanti per configurare il nuovo modulo. Il modulo sarà un modulo iOS. Successivamente denominiamolo “iOS”. Fate clic su Fine.

    Abbiamo quindi creato un'applicazione iOS in Android Studio. Se Android Studio vi indica di sincronizzare gli script Grade, fatelo. Nei passaggi successivi, creeremo un modulo “comune”, che sarà, come suggerisce il nome, il codice Java comune per le nostre applicazioni Android e iOS.

    Ora, procediamo creando un modulo “common” che conterrà le nostra logica applicativa condivisa (Java). Nel nostro semplice esempio, la nostra logica condivisa sarà un oggetto Java che ha un metodo chiamato sayHello() che riporta una stringa Java.

  11. Di nuovo nel pannello del progetto, clic destro e aggiungiamo un nuovo Modulo:
  12. Nella finestra del nuovo modulo, scegliete “Java Library” e fate clic su Avanti.
  13. Richiamiamo questa libreria che conterrà tutta la nostra logica applicativa (common) condivisa. Successivamente, denominiamola “common” e chiamiamo la nostra prima classe Java “AppLogic”. Modifichiamo anche il nome del pacchetto Java come i modelli generati per gli altri moduli. In generale, dovrebbe risultare questo: company_domain_in_reverse.appname.common, per esempio
    com.mycompany.myfirstapp.common

  14. Fare clic su Fine e lasciate che Android Studio aggiorni il pannello dei progetti e gli script Gradle.

    Aggiungeremo ora del codice alla nostra classe AppLogic.

  15. Accedere a common > java > com.mycompany.myfirstapp.common e aprite la classe AppLogic. Sostituite i contenuti con quanto segue (il codice in grassetto riguarda stringhe appena aggiunte/modificate):

    package com.mycompany.myfirstapp.common;

    public class AppLogic {
      private String myString;

      public AppLogic(){
       this.myString = "Hello World from common";
     }

      public String sayHello(){
       return this.myString;

    }
    }

    Infine aggiungiamo il modulo common come dipendenza nelle app Android e iOS. Nota: Vengono chiamate rispettivamente “app” e “iOS” nel pannello del progetto.

  16. Selezionate una root del modulo qualsiasi (ne avrete tre denominate app, iOS e common). Clic destro e scegliete Open Module Settings.
  17. Per i moduli bothapp e iOS aggiungete il modulo common nella scheda Dependencies. Per far ciò, fate clic sul segno + in basso e fate clic su Module Dependency e quindi scegliete common nell'elenco.

    Dopo aver aggiunto il modulo comune come dipendenza del modulo iOS, le impostazioni del modulo per iOS dovrebbero essere queste:

    Seguire quanto detto sopra anche per il modulo app:

  18. Il codice Java nel modulo common verrà compilato dal compiler Java. Il modulo è dotato del suo script Gradle* per il processo di costruzione. Dobbiamo aggiornare il nostro script per indicare a Gradle quale versione di Java deve essere usata per compilare il nostro modulo. Aprite lo script Gradle per il modulo common (Gradle Scripts > build.gradle (Module: common)) e aggiungete quanto segue al termine:

    compileJava {
      targetCompatibility = 1.7
      sourceCompatibility = 1.7
    }

    Ora, codifichiamo una piccola applicazione Android dotata di pulsante e campo di testo. Quando fate clic sul campo del testo, chiamate il metodo sayHello() dell'oggetto AppLogic condiviso.

  19. Per l'app Android, aprite il layout activity_main
    (app>res>layout>activity_main.xml). Se vedete del codice XML, fate semplicemente clic sulla scheda Design nella parte inferiore per passare all'interfaccia grafica. Dovrebbe essere già presente un campo di testo Hello World. Aggiungiamo un pulsante trascinandone uno dalla tavolozza al telefono. Doppio clic sul pulsante e rinominiamolo “Click Me!”. Prestate attenzione che l'ID del pulsante sia chiamato “button”. Android individua gli elementi a schermo tramite i loro ID. Il testo Hello World esistente ha come ID textView. Potete visualizzarlo sia nel pannello ad albero dei componenti o nel file XML (per visualizzare il codice XML, fate clic sulla scheda Text nella parte inferiore)


  20. Poi nella nostra MainActivity (app > package com.mycompany.myfirstapp > MainActivity), importiamo il nostro modulo common e aggiungiamo della logica al nostro pulsante appena creato (Vedere codice snippet 1). Le stringhe in grassetto sono parti di codice che sono state aggiunte. Per le classi come Button e View che vengono fornite nell'SDK Android, potete sempre premere Option+Enter per importare automaticamente i pacchetti pertinenti.

  21. Opzionale: Potete testare la nuova app Android su un dispositivo reale o un emulatore. Potete farlo modificando le configurazioni dell'app Android. Nel menu di configurazione, potete scegliere il dispositivo di destinazione. Consultate la documentazione ufficiale Android per maggiori informazioni sull'esecuzione di un'app su un dispositivo reale o un dispositivo virtuale.

Poi, creiamo l'app iOS.

  1. Dalla pagina dei progetti, aprite il file java AppViewController. (iOS > java > com.mycompany.myfirstapp > ui > AppViewController). Modificate il codice per importare il modulo common e aggiungete la logica necessaria al pulsante. Nota: è stato creato automaticamente un pulsante quando il modulo Multi-OS Engine Hello World è stato aggiunto. Vedere codice snippet 2 più sotto per tutto il codice. Le stringhe in grassetto sono quelle che sono state aggiunte/modificate.

  2. Il codice per la nostra app iOS è pronto. Successivamente, eseguiamo l'app iOS in iOS Simulator. Per farlo, scegliamo iOS dal menu a tendina come mostrato nella schermata seguente:

3.Ed ecco fatto! Ora potete eseguire una classica applicazione Hello World su Android e iOS con codice condiviso.

Ci siamo divertiti! E ora che possiamo fare? Potreste controllare gli altri nostri esempi più avanzati nella cartella degli esempi: /Applications/Intel/INDE/multi_os_engine/samples

Dateci pure uno sguardo. Se avete problemi, non esitate a fare domande sul nostro forum dedicato. Inoltre, non dimenticate i nostri blog per aggiornamenti e funzionalità riguardanti Multi-OS Engine.

    Code Snippet

    Code snippet 1 – Android (MainActivity.java) 

     

    package com.mycompany.myfirstapp;

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;


    /* Import our common module */
    import com.mycompany.myfirstapp.common.*;

    public class MainActivity extends AppCompatActivity {

       AppLogic al = new AppLogic();
       Button button;
       TextView tv;


       @Override
       protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);

         button = (Button) findViewById(R.id.button);
         tv = (TextView) findViewById(R.id.textView);

         button.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
             tv.setText(al.sayHello());
           }
         });

       }

       @Override
       public boolean onCreateOptionsMenu(Menu menu) {
         // Inflate the menu; this adds items to the action bar if it is present.
         getMenuInflater().inflate(R.menu.menu_main, menu);
         return true;
       }

       @Override
       public boolean onOptionsItemSelected(MenuItem item) {
         // Handle action bar item clicks here. The action bar will
         // automatically handle clicks on the Home/Up button, so long
         // as you specify a parent activity in AndroidManifest.xml.
         int id = item.getItemId();

         //noinspection SimplifiableIfStatement
         if (id == R.id.action_settings) {
           return true;
         }

         return super.onOptionsItemSelected(item);
       }
    }

     

    Code snippet 2 – iOS – AppViewController.java 

     

    package com.mycompany.myfirstapp.ui;

    import com.intel.inde.moe.natj.general.NatJ;
    import com.intel.inde.moe.natj.general.Pointer;
    import com.intel.inde.moe.natj.general.ann.Generated;
    import com.intel.inde.moe.natj.general.ann.Owned;
    import com.intel.inde.moe.natj.general.ann.RegisterOnStartup;
    import com.intel.inde.moe.natj.objc.ObjCRuntime;
    import com.intel.inde.moe.natj.objc.ann.ObjCClassName;
    import com.intel.inde.moe.natj.objc.ann.Property;
    import com.intel.inde.moe.natj.objc.ann.Selector;
    import com.mycompany.myfirstapp.common.AppLogic;

    import ios.NSObject;
    import ios.uikit.UIButton;
    import ios.uikit.UILabel;
    import ios.uikit.UIViewController;

    @com.intel.inde.moe.natj.general.ann.Runtime(ObjCRuntime.class)
    @ObjCClassName("AppViewController")
    @RegisterOnStartup
    public class AppViewController extends UIViewController {

       AppLogic al = new AppLogic();

       static {
         NatJ.register();
       }

       @Generated("NatJ")
       @Owned
       @Selector("alloc")
       public static native AppViewController alloc();

       @Generated("NatJ")
       @Selector("init")
       public native AppViewController init();

       @Generated
       protected AppViewController(Pointer peer) {
         super(peer);
       }

       public UILabel statusText = null;
       public UIButton helloButton = null;

       @Override
       @Selector("viewDidLoad")
       public void viewDidLoad() {
         statusText = getLabel();
         helloButton = getHelloButton();
       }

       @Selector("statusText")
       @Property
       public native UILabel getLabel();
       @Selector("helloButton")
       @Property
       public native UIButton getHelloButton();

       @Selector("BtnPressedCancel_helloButton:")
       public void BtnPressedCancel_button(NSObject sender){
         statusText.setText(al.sayHello());
       }
    }

    Uso della funzionalità multifinestra come differenziazione su Android*

    $
    0
    0

    Download PDF[PDF 1.2MB]

    Panoramica

    Multifinestra è una funzionalità del sistema operativo Android* in grado di fare la differenza sulle vostre app. Molti OEM e ODM quali Samsung, Ramos e Huawei impiegano funzionalità per promuovere i loro prodotti e farli risaltare rispetto ad altri prodotti. In questo articolo, introdurremo la funzione multifinestra e vi mostreremo come implementarla nelle app.

    Figura 1. Casi d'uso di multifinestra

    Introduzione

    In June, 2012, the first open source multi-tasking framework, called Cornerstone, was developed. In August 2012, Samsung launched the first multi-window commercial product. And from 2013 until now, there has been an explosion of multi-window solutions on the market (see Figure 2).

    Figura 2. Evoluzione multifinestra

    I due tipi di stili multifinestra sono: fluttuante o ancorata. La funzione multifinestra di solito include le funzioni apri/chiudi, ridimensiona e scambia. La funzione apri/chiudi avvia/interrompe la funzionalità. La funzione ridimensiona consente di modificare le dimensioni della finestra. La funziona scambia consente di scambiare la posizione delle finestre.

    Figura 3. Stili di finestre multifinestra

    Nel 2013 sono emerse sul mercato diverse soluzioni, sviluppate da OEM/ODM, da fornitori di software indipendenti (ISV) e dalle comunità open-source. La tabella seguente compara le diverse soluzioni multifinestra.

    CaratteristicaCornerstoneStandoutXposedTieto
    DescrizioneFramework multi-tasking per il sistema operativo Android*Android* Una libreria open source utilizzabile per creare app fluttuantiUn'applicazione multifinestra che supporta finestre ancorateIl progetto mira a creare un'esperienza utente simile a quella desktop
    Apri/chiudi, ridimensiona, ingrandisci al massimoSupportatoSupportatoSupportatoSupportato
    Stile finestraAncorataFluttuanteAncorataAncorata/Fluttuante
    Modifica codiceFramework AndroidStrato applicazioneFramework AndroidFramework Android
    Supporto applicazioneSupporta tutte le applicazioni, ma SurfaceView non è regolabile dinamicamenteAlcune applicazioni assistenti, ad esempio, calcolatori, ecc.Occorre migliorare la compatibilità e stabilità dell'applicazioneSupporta tutte le applicazioni
    Versione AndroidAndroid 4.1 ~Android 4.4Android 4.1~
    Android 4.4
    Android 4.4Android 4.4
    Sito web ufficialehttp://www.onskreen.comhttp://forum.xda-developers.com/showthread.php?t=1688531http://forum.xda-developers.com/xposedhttps://github.com/tieto/multiwindow_for_android

    Architettura software

    Potete modificare il codice del framework Android per adattare più funzioni. L'architettura del sistema operativo Android è divisa in strati.

    Per Android 4.2 e Android 4.3, il programma di avvio e altre applicazioni vengono tutte eseguite in uno stack, chiamato “stack principale”. Come sappiamo, la multifinestra necessita di più stack per contenere più finestre, quindi ci occorre modificare la classe ActivityManagerService del framework per aggiungere la creazione dello stack e l'interfaccia di gestione dello stack. Per modificare la classe WindowManagerService del framework per adattare la visuale, dobbiamo modificare l'inputManager del framework per distribuire l'evento touch alle finestre corrispondenti.

    La gestione dello stack è stata cambiata significativamente quando sono stati rilasciati Android 4.4 e Android 5.0. Il programma di avvio e le altre applicazioni possono essere eseguiti su stack diversi. Sono stati aggiunti stack e funzioni di gestione stack. Di seguito sono mostrate le differenze tra le revisioni Android.

    Stack management changes between Android* 4.3 and Android 4.4

    Figura 4. Modifiche della gestione stack tra Android* 4.3 e Android 4.4

    Concentriamoci su Android 5 nome in codice Lollipop. Come sappiamo, il sistema operativo Android* usa un metodo callback per attivare la funzione di interfaccia dell'attività. Ma la funzione principale viene realizzata sul framework, quindi introdurremo due classi importanti ActivityManagerService e WindowManagerService.

    Figura 5. Struttura software di Lollipop

    Gestione attività di Lollipop

    Dato che la funzionalità multifinestra dipende dallo stack, quanto segue mostra come creare uno stack e come avviare un'attività su uno stack.

    In Lollipop, IactivityManager.java ha aggiunto le seguenti funzioni di interfaccia.

    Tabella 1.Modifiche del codice sorgente di Lollipop

    IactivityManager.java aggiunta nuove funzioni di interfacciaDescrizione
    public void moveTaskToStack(int taskId, int stackId, boolean toTop)Spostare l'attività su un altro stack
    public void resizeStack(int stackBoxId, Rect bounds)Ridimensionare le dimensioni di stack
    public void setFocusedStack(int stackId)Impostare il focus stack corrente
    Public Boolean isInHomeStack(int taskId)ottenere l'attività se si trova in HomeStack

    Dopo l'avvio, il processo SystemServer avvierà i servizi di gestione dell'attività e i servizi di gestione della finestra. Possiamo aggiungere le frasi RuntimeException per tracciare il processo.

    Progress of stack creation in Lollipop

    Figura 6. Progresso della creazione dello stack in Lollipop

    Ora mostriamo come avviare un'attività su uno stack.

    Start activity on a stack

    Figura 7. Avviare attività su uno stack

    In lollipop, adb (android debug bridge) ha aggiunto i seguenti comandi.

    Tabella 3. Nuovi comandi adb di Lollipop

    COMANDI ADBFunzioneDescrizione
    Adb shell am stack startAvvia una nuova attività su <DISPLAY_ID> tramite IntentKitkat 4.4, adb commands contain adb shell am stack create.
    Lollipop 5.0, adb commands adb shell am stack create deletion
    Adb shell am stack movetaskSposta <TASK_ID> dallo stack attuale al di sopra o al di sotto di STACK_IDUso: adb shell am stack movetask task_id stackid true/false
    Nota: funziona su KitKat, ma non funziona su Lollipop.
    Adb shell am stack resizeModifica le dimensioni e posizione di <STACK_ID> a <LEFT, TOP, RIGHT, BOTTOM>Uso: adb shell am stack resize task_id weight

    Gestione finestra di Lollipop

    WindowManagerService è il gestore di finestre principale. La sua funzione contiene invio di eventi input, layout schermo e gestione superfici.

    WindowManagerService role in the graphics architecture

    WindowManagerService role in the graphics architecture 2

    Figura 8. Il ruolo di WindowManagerService nell'architettura grafica2

    Alcune domande comuni su multifinestra

    Multifinestra è dotato di una funzione di ridimensionamento. Abbiamo visto casi dove un'animazione di gioco non può essere ridimensionata. Il problema alla radice sta nel fatto che la funzione Android SurfaceFlinger non può regolare dinamicamente la dimensione.

    Games using SurfaceFlinger can’t dynamically adjust the windows size

    Figura 9. I giochi che usano SurfaceFlinger non regolano dinamicamente le dimensioni della finestra

    Un altro problema riguarda la non corretta visualizzazione di alcune applicazioni in multifinestra. Un esempio di seguito mostra il calcolatore non visualizzato correttamente in multifinestra perché l'applicazione usa una configurazione di compatibilità non corretta.

    Calculator with bad configuration

    Figura 10.Calcolatore con configurazione non corretta

    La prossima versione di Android supporterà il multifinestra?

    Google inserirà la funzionalità multifinestra nella sua prossima versione del sistema operativo. Ho trovato le seguenti informazioni di log nel codice sorgente di Lollipop. Useremo il seguente comando per cercare nel log multifinestra.

    git log --grep “multiwindow”

    Il log contiene una stringa che dice “defer tap outside stack until multiwindows”. Quindi possiamo presumere che il multifinestra sarà sulla tabella di marcia di Google.

    Lollipop log about multi-window

    Figura 11.Il log di Lollipop su multifinestra

    Caso di studio: Cornerstone

    Onskreen ha sviluppato Cornerstone, la prima soluzione framework multifinestra. Destinato a dispositivi e tablet con schermo grande. Potete scaricare il codice sorgente da GitHub3. È supportato solo sulle versioni Android 4.1 e Android 4.2. Non è stato ancora rilasciato su versioni Android più recenti. Ma possiamo analizzare il codice sorgente di Android 4.2 per ottenere maggiori dettagli tecnici.

    Cornerstone modifications on Jelly Bean

    Figura 12. Modifiche di Cornerstone su Jelly Bean

    Sommario

    Molti dispositivi mobili ora utilizzano processori Intel® con sistema operativo Android. Gli sviluppatori come possono migliorare l'esperienza utente? Il loro prodotti come possono competere al meglio? Queste domande ci spingono costantemente a migliorare i nostri prodotti su dispositivi con architettura Intel® (IA). Multifinestra è una buona funzionalità che fa la differenza. È conveniente e consente ai consumatori di eseguire due o più cose contemporaneamente. Possono guardare un video e usare messaggistica istantanea con feedback video. Possono giocare a un videogioco e leggerne recensioni. Diversi dispositivi ora supportano la funzionalità multifinestra: Tablet Ramos i12, tablet Teclast x98 e Cube i7, che usa il sistema operativo Remix.

     

    Multi-window feature on IA devices

    Figura 13.Multifinestra su dispositivi IA

    Riferimenti

    [1] http://www.onskreen.com/cornerstone/

    [2] http://himmele.googlecode.com/svn/trunk/Google%20Android/Android%20Graphics%20Architecture.pdf

    [3] https://github.com/Onskreen/cornerstone

    Risorse

    http://www.customizeblogging.com/2015/04/android-6-0-muffin-concept-video-shows-multi-windows-quick-reply-feats.html

    Informazioni sull’autore

    Li Liang ha ottenuto il master in elaborazione di segnale e informazioni dalla Changchun University of Technology. È entrato in Intel nel 2013 come application engineer nel Reparto Relazioni Sviluppatori CCE (Client Computing Enabling). Si concentra sull'assistenza agli sviluppatori per differenziare le loro app su piattaforma Android.


    Collegamento a Intel® Edison da Android* con Bluetooth* LE (BLE)

    $
    0
    0

    Introduzione

    L'uso della comunicazione Bluetooth* LE (BLE) sta vivendo un boom sia nei prodotti commerciali che in ambito hobbystico, principalmente grazie al costo ridotto e ai requisiti energetici minimi. Tutto ciò lo rende un'ottima scelta quando si desidera comunicare dal proprio telefono o tablet Android* verso i progetti Intel® Edison o Intel® Galileo.

    Lo scopo che si prefigge questo documento è di mostrarvi come scrivere il codice e collegare l'hardware per stabilire una comunicazione BLE tra un Intel Edison e un dispositivo Android dotato di Bluetooth 4.0, tramite software gratuito e hardware a costi contenuti.

    Che cos'è BLE?

    Bluetooth Low Energy, Bluetooth LE, o semplicemente BLE (noto anche come Bluetooth Smart) è una tecnologia di rete personale wireless progettata e commercializzata da Bluetooth Special Interest Group. È destinata ad applicazioni nel settore sanitario, del fitness, della protezione, dell'automazione e dell'home entertainment.

    Bluetooth LE era stato originariamente presentato con il nome di Wibree da Nokia nel 2006. È stato aggiunto allo standard Bluetooth nel 2010 con la versione Bluetooth 4.0.

    BLE consente ai dispositivi di consumare sensibilmente meno energia delle normali connessioni Bluetooth, tuttavia offrendo la stessa connettività di un regolare Bluetooth, con circa la metà del raggio d'azione (circa 15 metri). I dispositivi alimentati a batterie che utilizzano Bluetooth LE sono in grado di funzionare per anni senza che si debbano ricaricare o sostituire le batterie. I dispositivi Beacon come quelli di Estimote dichiarano già una durata della batteria di tre (3) anni (www.estimote.com).

    Hardware

    Ci concentremo su Intel Edison, ma la maggior parte del contenuto è applicabile anche a Intel Galileo. Per il nostro progetto IoT, i sensori e controlli fisici che utilizzeremo provengono dal sistema Grove di Seeed Studio. Nello specifico, impiegheremo:

    • Intel Galileo con
    • Seeed Grove – Starter Kit Plus Intel® IoT Edition per Galileo GEN 2
    • Seeed Grove BLE
    • Un dispositivo Android dotato di Android 4.3 o superiore (Ho usato un Lenovo TAB S8-50)
    • Un PC con Windows* 7 o 8 per lo sviluppo (Ho usato un Dell XPS12)

    Un paio di note sull'hardware:

    1. Il Grove Starter Kit indica che è stato progettato per Intel Galileo, ma funziona bene con Edison. Volendo è possibile acquistare singolarmente i componenti Grove ma il kit è più economico.
    2. Ho usato il mio tablet Lenovo Android durante lo sviluppo ma qualsiasi dispositivo Android con almeno Android 4.3 e supporto per Bluetooth 4.0 dovrebbe andar bene.
    3. Ho usato il mio Dell XPS12 per scrivere il codice per Intel Edison e il progetto Android (e questo articolo). Lo sviluppo può essere eseguito anche su sistemi Mac* o Linux*.

    Software

    Ho impiegato diversi strumenti software gratuiti. Per procedere seguendo questo esempio, dovrete scaricarli e installarli se necessario:

    Tutto il software di cui sopra è disponibile per Windows, Mac e Linux, ma qui parlerò nello specifico solo dell'installazione su Windows.

    Uno sguardo da vicino all'hardware

    Intel® Edison

    Intel® Edison è la prima serie proposta di piattaforme di calcolo generiche e a costi contenuti. È progettata per consentire la realizzazione rapida e semplice di prototipi di progetti IoT fornendo un percorso pronto all'uso per la commercializzazione.

    Intel® Edison impiega un SoC Intel® da 22nm che include una CPU dual-core Intel® Atom™ a 500MHz. Supporta 40 GPIO e include RAM LPDDR3 da 1GB, EMMC da 4GB per l'archiviazione e Wi-Fi* e Bluetooth dual band in un minuscolo fattore di forma.

    Al suo interno gira un kernel Linux e per ottenere le prestazioni migliori da Edison, dovrete scrivere il codice Linux a livello hardware.

    Tuttavia Edison Linux contiene inoltre un'implementazione Arduino come programma Linux. In poche parole, significa che potete scrivere sketch per Arduino ed eseguirli sulla scheda Edison. Ed è esattamente ciò che andremo a fare.

    Per maggiori informazioni su Intel Edison qui: http://www.intel.com/content/www/us/en/do-it-yourself/edison.html

     

    Scheda di breakout Arduino

    La scheda di breakout Arduino per Intel Galileo serve a due finalità. Primo, fornisce una piattaforma di prototipazione più grande per un facile accesso ai pin IO. E secondo, fornisce una piattaforma hardware compatibile con Arduino, in modo da potere utilizzare scudi Arduino con Intel Edison (proprio come Intel Galileo). La figura 1 mostra Edison montato sulla scheda di breakout Arduino.

    Figura 1. Intel® Edison montato sulla scheda di breakout Arduino

    Grove Starter Kit Plus

    Il nome completo del kit è “Grove Starter Kit Plus – Intel® IoT Edition for Intel® Galileo Gen 2 Developer Kit” ed è stato progettato originariamente per le schede di 2a generazione Intel Galileo. Fortunatamente, è totalmente compatibile con Intel Edison tramite la scheda di breakout Arduino.

    Il kit (mostrato in Figura 2) è progettato per semplificare il lavoro e la prototipazione con sensori, attuatori e scudi. Contiene uno scudo compatibile con Arduino con connettori a quattro (4) pin. Questi connettori alimentano le porte IO che collegano i cavi inclusi che si fissano facilmente ai sensori e ai controlli nel kit. Ciò significa che potete realizzare progetti senza la necessità di perdervi con piccoli fili e resistori pull up/pull down, o preoccuparvi della polarità.

    Per saperne di più o acquistare il kit fare clic qui: http://www.seeedstudio.com/depot/Grove-starter-kit-plus-Intel-IoT-Edition-for-Intel-Galileo-Gen-2-p-1978.html

    Il creatore del kit Grove, Seeed Studios, fornisce diverse risorse utili online.

    Nello specifico, consiglio di clonare o scaricare la repository Sketchbook Starter qui: http://Github.com/Seeed-Studio/Sketchbook_Starter_Kit_V2.0

    E inserire tra i preferiti la pagina Grove Wiki qui: http://www.seeedstudio.com/wiki/index.php?title=Main_Page#Grove

     

    Figura 2. Grove Starter Kit Plus – Intel® IoT Edition per Intel® Galileo Gen 2 Developer Kit

    Grove BLE V1

    Useremo il modulo v1 Grove Bluetooth Low Energy, che non è incluso nello starter kit, ma è compatibile con i pin dello scudo Grove e i cavi connettori. Si tratta inoltre di un'applicazione aggiuntiva BLE relativamente poco cara, e al termine della stesura dell'articolo era l'opzione più economica che ho trovato.

    Grove BLE v1 si basa sullo standard del settore CC2540 di Texas Instruments. Diversi dispositivi impiegano questo chip. Se avete un altro modulo BLE CC2540 TI, come RedBear BLE Mini, dovreste poter adattare il codice d'esempio senza grandi problemi.

    Per saperne di più su Grove BLE v1 qui: http://www.seeedstudio.com/wiki/index.php?title=Grove_BLE_v1&uselang=en

    Va tenuto presente che Intel® Edison non include un modulo wireless sulla scheda che supporti Wi-Fi e Bluetooth 4.0/BLE; tuttavia, il modulo Grove BLE andrà a semplificare la configurazione hardware e software. Usare Grove BLE (Figura 3) significa anche che questi progetti possono essere adattati facilmente a Intel Edison.

    Figura 3. Modulo Grove BLE V1

    Debug su dispositivi Android

    Il supporto per BLE è stato aggiunto ad Android nella versione 4.3 (API livello 18). Occorre un dispositivo con la versione 4.3 o superiore per comunicare tramite BLE.

    Per saperne di più su BLE Android qui: https://developer.android.com/guide/topics/connectivity/bluetooth-le.html

    Se non siete esperti di sviluppo su Android, occorre abilitare le opzioni sviluppatore sul telefono o sul tablet prima di potere utilizzarlo per eseguire il debug del software. Aprite l'app di impostazione, scorrere in basso, selezionate “Info sul dispositivo” e fate clic sul numero della build sette (7) volte per sbloccare le opzioni sviluppatore.

    Le opzioni sviluppatore saranno visualizzate sotto le impostazioni; accertatevi di selezionare “Debug USB”.

    Per saperne di più sulle opzioni sviluppatore Android qui: http://developer.android.com/tools/device.html

     

    Installazione del software e preparazione alla codifica!

    Arduino IDE per Intel® Galileo

    Occorre scaricare la versione appositamente preparata per IDE Arduino per implementare gli sketch in Intel Edison o Galileo. Al momento della stesura dell'articolo la versione attuale è 1.5.3 ed è disponibile qui:

    https://software.intel.com/it-it/get-started-arduino-install

    Driver Intel® Edison

    Occorre inoltre scaricare e installare i driver Intel Edison dal link indicato qui sopra. Dovrebbe essere l'ultimo link nella pagina elencato sotto “Driver Software”. Al momento della stesura la versione è 1.0.0.

    Esiste inoltre un'eccellente Guida introduttiva se servono ulteriori istruzioni:

    software.intel.com/iot/getting-started

    Android Studio

    Android Studio è il nuovo IDE Java* per lo sviluppo su Android basato su IntelliJ IDEA* (https://www.jetbrains.com/idea/). Al momento è in beta, ma è stabile e abbastanza completo nelle sue funzionalità. Se vi trovate bene a usare Eclipse* per lo sviluppo Java Android o IntelliJ IDEA, non dovreste avere problemi a seguire la guida passo passo con entrambi.

    Android Studio semplifica il processo di installazione includendo l'SDK Android. È sufficiente scaricare, estrarre il contenuto del file zip ed eseguire studio.exe nella cartella bin.

    Per saperne di più su Android Studio qui: https://developer.android.com/sdk/installing/studio.html

     

    Android SDK

    Potreste dover scaricare dei pacchetti SDK aggiuntivi. In questo caso, fate clic su “SDK Manager” sulla barra degli strumenti in Android Studio. La configurazione degli SDK Android non rientra nei nostri scopi, ma potete ottenere informazioni aggiuntive qui:

    https://developer.android.com/sdk/installing/adding-packages.html

    Se avete precedentemente installato gli SDK Android, potete configurare Android Studio e indirizzarlo sul percorso corretto, come mostrato in Figura 4

    In Android Studio, fare clic su Configure -> Project Defaults -> Project Structure e impostare il percorso.

    Figure 4. Setting the SDK path in Android* Studio

    Test di Intel® Edison

    Prima di iniziare la spiegazione di seguito, accertatevi di poter eseguire lo sketch di esempio Blink. È incluso nel pacchetto di download di Arduino IDE nella cartella examples -> 01.Basics -> Blink.

    Per maggiori informazioni fare riferimento alla guida introduttiva di Edison:

    https://communities.intel.com/community/makers/edison/getting-started

    Android Hello World

    Una volta installato Android Studio, accertatevi di poter creare un nuovo progetto ed eseguirlo sul vostro dispositivo Android.

    1. Collegate il dispositivo Android al PC
    2. Aprite Android Studio
    3. Selezionate “New Project…”
    4. Selezionate un nome e un percorso e fate clic su “Avanti” 3 volte (API 15/Blank Activity)
    5. Fate clic su Fine e attendete la creazione del progetto (possono volerci più di 20 secondi)
    6. Premere l'icona Play verde sulla barra degli strumenti
    7. Selezionate il vostro dispositivo e premere “OK”

    Se tutto è stato eseguito correttamente, dovreste vedere “Hello world!” sullo schermo del vostro Android (Figura 5).

    Figura 5. App Android* Studio Hello World

    Come funziona BLE?

    BLE funziona fornendo piccoli pacchetti di dati quando necessario e spegnendosi successivamente. Questo è in parte uno dei motivi per cui Bluetooth LE usa così poca energia. Invece del tradizionale approccio di abbinamento di un normale Bluetooth, i dispositivi BLE si collegano soltanto quando occorre inviare o ricevere informazioni.

    BLE è fortemente strutturato nel modo di comunicare. I dispositivi espongono i servizi per inviare e ricevere i dati, e questi servizi sono dotati di quello che viene chiamato Characteristics che definisce quali dati possono essere condivisi. Per ulteriori dettagli, Characteristics può avere descrittori che consentono di definire i dati. Ad esempio, in caso di un servizio chiamato “Heart Rate Monitor” che comprende caratteristiche quali la “misurazione del battito cardiaco”.

    La maggior parte delle API Bluetooth LE consentono la ricerca di dispositivi locali e il ritrovamento di servizi, caratteristiche e descrittori su questi dispositivi.

    Termini e concetti di BLE Key

    Qui abbiamo un breve riassunto dei termini e dei concetti della BLE key che occorre comprendere prima di iniziare un progetto BLE:

    Generic Attribute Profile (GATT)

    Il profilo GATT è una specifica generale per l'invio e la ricezione di piccole parti di dati note come “attributi” su link Bluetooth a bassa consumo. Tutti i profili applicativi LE attuali si basano su GATT. Il Bluetooth Special Interest Group (SIG) (https://www.bluetooth.org) ha definito preventivamente una serie di profili per i dispositivi BLE. Questi profili sono specifiche che descrivono come può essere utilizzato un dispositivo.

    Attribute Protocol (ATT)

    Attribute Protocol (ATT) è dove GATT è realizzato. ATT è un protocollo ottimizzato progettato specificatamente per dispositivi BLE. La comunicazione ATT invia il minor numero di byte di dati possibile. Ciascun attributo è dotato di un identificatore unico universale (UUID), che è una stringa ID a 128 bit standardizzata impiegata per identificare univocamente un'informazione. Gli attributi trasportati da ATT sono formattati come caratteristiche e servizi (definiti qui sotto).

    Charactteristiche

    Una caratteristiche contiene un singolo valore e 0 o più descrittori (sotto) per descrivere il valore della caratteristica.

    Descrittore

    I descrittori sono attributi definiti che descrivono un valore di una caratteristica. Può trattarsi di descrizioni leggibili all'uomo, unità o misure specifiche, o definire un intervallo di valori accettabile.

    Servisio

    I servizi sono raccolte di caratteristiche. Potete trovare un elenco dei profili basati su GATT esistenti qui: https://developer.bluetooth.org/gatt/services/Pages/ServicesHome.aspx

    Invio di dati da Android a Intel® Edison

    Prerequisiti

    Il resto di questo documento presume che abbiate un sistema di sviluppo impostato e configurato sia per lo sviluppo su Intel Edison che Android. Accertatevi di aver completato i seguenti passaggi e riguardare quanto detto in precedenza se necessario.

    • Installare IDE Intel Arduino
    • Installare i driver Intel Edison
    • Installare Android Studio
    • Installare Android SDK
    • Implementare ed eseguire la demo di Blink su Intel Edison
    • Implementare ed eseguire il progetto Android vuoto di Hello world

    BLE su Android

    Potete scaricare il progetto completo da GitHub qui:

    https://github.com/adrianstevens/Edison_to_Android_BLE/tree/master/Android/BLEConnect

    Tuttavia consiglio di creare il vostro progetto personale e riportare il codice stringa per stringa facendo riferimento al link di cui sopra.

    Creazione di un nuovo progetto

    Aprite Android Studio (o il vostro IDE a scelta), create una nuova applicazione Android vuota e denominatela BLEConnect. Accertatevi di impostare il Minimum SDK almeno su API 18. In caso contrario non potrete utilizzare le API BLE.

    Figura 6. Creazione di una nuova applicazione Android

    Successivamente aggiungere i permessi necessari aprendo AndroidManifest.xml, e aggiungendo quanto segue sopra la tag <application>:

    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

    Impostare l'interfaccia grafica

    Cominciamo assemblando l'hardware di base. Se non lo avete già fatto, montate Intel Edison sulla scheda di breakout Arduino.

    In seguito, montate lo scudo Grove allineando i pin sulla parte inferiore dello scudo con la scheda di breakout Arduino. Successivamente connettete Grove BLE v1 alla porta seriale UART.

    Figura 7. Impostare l'id risorsa per TextView

    MainActivity

    Per questo progetto, il resto del codice va in MainActivity. Se si aggiunge il codice stringa per stringa, vedrete che Android Studio rileva automaticamente le importazioni non realizzate e vi indica di aggiungerle.

    Il codice di esempio effettua quanto segue:

    1. Verifica che BLE sia supportato sul dispositivo Android
    2. Ricerca i dispositivi BLE nelle vicinanze
    3. Identifica e si collega al modulo BLE Grove
    4. Ricerca i servizi disponibili per i servizi di comunicazione noti
    5. Trova la caratteristica di trasmissione sul servizio di comunicazione
    6. Invia un messaggio scrivendo un valore sulla caratteristica

    Non starò a spiegare ogni stringa del codice qui, ma daremo uno sguardo ai concetti fondamentali.

    Variabili di classe e valori statici

    Archivieremo una serie di valori e ci collegheremo al modulo BLE, ricercheremo servizi e invieremo il nostro messaggio. Aggiungeremo poi alcuni valori statici noti per Grove BLE v1 (TI CC2540). Potreste dover modificarli se utilizzate un modulo diverso. Nello specifico, consiglio di definire le caratteristiche di trasmissione e ricezione, ad esempio:

    CHARACTERISTIC_TX = "0000ffe1-0000-1000-8000-00805f9b34fb"
    CHARACTERISTIC_RX = "0000ffe1-0000-1000-8000-00805f9b34fb"

    Stato del metodo helper

    Per semplicità, mostriamo il nostro svolgimento sul TextView denominato in precedenza. Il codice include un semplice metodo helper chiamato statusUpdate che utilizziamo per scrivere messaggi di stato allo schermo e alla console. Inoltre riporta al thread dell'interfaccia grafica in modo da poter richiamarla senza problemi da qualsiasi thread.

    Collegare a un dispositivo BLE

    Per ottenere un riferimento a Bluetooth Manager innanzitutto verifichiamo che BLE sia disponibile sul nostro dispositivo, chiamiamo getSystemService per ottenere un riferimento a Bluetooth Manager (BluetoothManager), e poi chiamiamo il metodo getAdapter() per ottenere il nostro riferimento all'oggetto BluetoothAdapter. In alternativa, potete usare il metodo helper statico getDefaultAdapter direttamente dalla classe Bluetooth Manager.

    Cercate dispositivi BLE nelle vicinanze

    Per cercare i dispositivi, usiamo un timer per cercare entro un periodo di tempo impostato. Chiamiamo startLeScan sul nostro oggetto Bluetooth Manager e passiamo a un oggetto callback per venire notificati quando vengono trovati dei dispositivi.

    L'API ricerca in continuazione i dispositivi e come risultato, dovremmo ottenere diverse notifiche in LeScanCallback per ogni dispositivo, in modo da verificare che la voce del dispositivo sia univoca prima di salvarla. Controlliamo inoltre i nomi del dispositivo per il nostro modulo e salviamolo come riferimento. Ad esempio non ci interessa davvero salvare i dispositivi nell'elenco.

    
    @Override
    public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord)
    {…
    }
    

    Trovate il servizio di comunicazione

    La maggior parte dei dispositivi BLE espone uno o più servizi per la comunicazione/interazione.  Il chip TI CC2540 nel nostro BLE Grove è dotato di una chiave di servizio con ID “0000ffe0-0000-1000-8000-00805f9b34fb”. Successivamente troviamo e salviamo un riferimento su quel servizio.

    Per prima cosa occorre collegarsi al dispositivo. Per ricevere le notifiche quando si è connessi o quando vengono trovati dei servizi, ci occorre un oggetto BluetoothGattCallback ed eseguiamo l'override di onConnectionStateChanged e onServicesDiscovered.

    Tenete presente che nel metodo onConnectionStateChanged, quando viene notificata una connessione chiamiamo mBluetoothGatt.discoverServices() per ricercare i dispositivi. Una volta che abbiamo identificato il servizio che vogliamo, possiamo procedere e inviare un messaggio.

    @Override public void onConnectionStateChange (BluetoothGatt gatt, int status, int newState) { … } 

    @Override public void onServicesDiscovered (BluetoothGatt gatt, int status) { … }

    È possibile eseguire l'override di una serie di altri metodi. Vedere la documentazione qui:

    https://developer.android.com/reference/android/bluetooth/BluetoothGattCallback.html

    Invio di un messaggio

    Nel codice di esempio è presente un metodo sendMessage. Identifichiamo la caratteristica desiderata dal suo UDID e chiamiamo setValue sulla caratteristica. Infine, chiamiamo writeCharacteristic sul nostro riferimento BluetoothGatt, passando la caratteristica come valore per l'invio dei dati.

    Sono presenti diversi overload di setValue ed esiste a dire il vero un overload più semplice per inviare stringhe, ma dato che molte comunicazioni BLE inviano comandi come byte, si tratta di un esempio più utile.

    E ora vediamo come impostare Intel Edison.

    Impostazione di Intel® Edison con la scheda di breakout Grove e il modulo BLE

    Start by assembling the basic hardware. If you haven’t already, mount the Intel Edison to the Arduino breakout board.

    Next, mount the Grove shield by aligning the pins on the bottom of the shield to the Arduino breakout board. Then connect the Grove BLE v1 to the serial UART port.

    Figura 8. Intel® Edison sullo scudo Grove e il modulo BLE collegato

    Il nostro primo sketch

    Andremo ad eseguire alcune semplici comunicazioni seriali tra il nostro dispositivo Android e Intel Edison. Ma vogliamo anche vedere che cosa viene inviato e ricevuto e quindi useremo il monitor serial integrato di Arduino IDE.

    Potete vedere una versione completa dello sketch qui:

    https://github.com/adrianstevens/Edison_to_Android_BLE/tree/master/Sketches/SimpleSerial

    Aprite l'IDE di Intel Arduino e create uno sketch nuovo. Salviamolo e denominiamolo “SimpleSerial”. Diversamente da altre schede compatibili con Arduino, Intel Edison è dotato di due porte seriale che possiamo utilizzare. Ciò è particolarmente utile perché ci consente di comunicare dal nostro PC a Edison mentre Edison invia e riceve i dati tramite Grove BLE. L'UART seriale primario è accessibile tramite la microUSB connessa al vostro PC, e possiamo utilizzare il connettore UART sullo scudo Grove che è collegato al modulo BLE.

    Il nostro sketch viene eseguito automaticamente una volta che è implementato su Intel Edison. Prima esegue la funzione setup(), e quindi chiama consecutivamente la funzione loop() indefinitivamente. Ciò consente di leggere e rispondere agli input in entrata dai collegamenti seriali.

    Inizializzazione dei collegamenti seriali

    La velocità di comunicazione predefinita di Grove BLE è di 9600 baud, quindi iniziamo da questo. Ci occorre configurare entrambe le porte seriali per usare questa velocità. Dobbiamo inoltre inviare un paio di comandi AT a Grove BLE per ripristinarlo alle impostazioni predefinite. Potete vedere tutto ciò nella funzione setup() dello sketch.

    Tenete presente che stiamo prima configurando “Serial”, che è la porta microUSB UART, e successivamente “Serial1”, che è l'UART connesso a Grove BLE.

    Il loop

    Tutto ciò che eseguiamo in questo sketch è leggere dati dalla porta seriale e inviarli all'altra. Per far ciò, chiamiamo la funzione lettura() sulle porte seriali, che ci dà un carattere singolo e quindi stampa() sull'altra porta seriale.

    Edison esegue il loop abbastanza rapidamente da non avere problemi a stare dietro ai 9600 baud.

    Implementazione dello sketch

    Fate clic sul pulsante di verifica sull'IDE di Arduino (la spunta) e sistemate eventuali errori. Una volta verificato, accertatevi che Intel Edison sia collegato al PC e caricate lo sketch (freccia destra). Una volta completato il trasferimento, lo sketch avvia il loop e siamo pronti a collegarci dall'app Android. Ora apriamo il Serial Monitor sull'IDE Arduino (la lente d'ingrandimento in alto a destra) in modo da poter inviare e ricevere dati.

    Una volta che lo sketch è in esecuzione su Intel Edison, eseguire l'app Android BLEConnect. Dovreste vedere il messaggio “Hello Grove BLE” comparire nel monitor seriale.

    Se non funziona, potrebbe trattarsi di un problema con l'app Android. Verificare il display di stato che dovrebbe indicare dove si trova il problema.

    C'è anche uno sketch nella repo GiftHub che visualizza il messaggio sul LCD Grove. Accertatevi che il vostro scudo Grove sia impostato a 5V e collegate il display LCD a uno dei collegamenti I2C.

    Figura 9. BLEConnect in esecuzione su un telefono Android

    Figura 10. Arduino IDE Serial Monitor riceve il messaggio BLEConnect

    Continuazione

    La creazione di un progetto più complesso significa impiegare dell'architettura sia nel codice Android che nello sketch. Consiglierei di spostare la maggior parte del codice BLE Android in un servizio per astrarlo dall'interfaccia grafica e renderlo semplice da usare su più attività e progetti. Quando si creano sketch più avanzati, vorrete usare Arduino Time Library, che consente di simulare l'esecuzione di più loop durante la ricezione di dati (http://playground.arduino.cc/Code/Time). Aggiungerò esempi alla repository GitHub (https://github.com/adrianstevens/Edison_to_Android_BLE), e ne discuterò in un articolo futuro.

    Informazioni sull’autore

    Adrian Stevens ha oltre 14 anni di esperienza nello sviluppo di applicazioni mobili, specializzato in sviuppo multipiattaforma di C# e C++. La conoscenza di Adrian comprende architettura dell'interfaccia utente, elaborazione audio e di segnale, sensori e matematica. Con base a Vancouver, in Canada, Adrian è appassionato di tecnologia e un grande spirito imprenditoriale. Collabora all'esecuzione dello sviluppo di una multipiattaforma C# su Meetup.

    Adrian ha prima cominciato con lo sviluppo di applicazioni mobili nel 2001 per piattaforme come Palm Pilot e Pocket PC. È riuscito a fondare e condurre uno studio di sviluppo per dispositivi mobili. Adrian è attualmente istruttore di applicazioni mobili e multipiattaforma e insegna strategie per architettura e sviluppo.

    Indice

    Kid at Heart: Back to Basics in 2016

    $
    0
    0

    We’ve come a long way since the days of Pong and Dungeons and Dragons, but the lasting principles of interactive video gaming remain.

    Video games can be considered a fun pastime, or even a way to kill some time, perhaps when stuck inside dealing with the type of winter weather recently experienced. But often overlooked are the benefits this form of entertainment has provided to us over the years, and continues to provide in our lives. Whether it’s a way to spend time enjoying a shared interest with your kids, a competitive outlet, a way to stimulate your brain’s problem-solving skills, or simply a relaxation method, the value of the activity itself can’t be denied.

    Atari’s Pong is often recognized as one of the earliest video games available in the U.S. The first version debuted in November 1972 as the mid-70s video game craze really took off.1 During this period, Dungeons and Dragons, the game that launched the modern role-playing genre, also became a hit, in 1974. And while the simplicity of these classics may be viewed with some puzzlement by today’s technologically-advanced generation, let’s face it – the compelling basic principles of fun, make-believe, and even a little strategic competition, all of which video games provide, haven’t changed much at all.

    The image of a group of friends, or family members, gathered around a TV four decades ago, or today in front of individual mobile devices, is commonplace. But while the driving principles have remained the same, the imagery and overall gaming experience have transformed to a new level – one that better suits today’s digital world.

    The following apps exemplify the perfect balance of the original reasons for enjoying high-tech games, and the best of today’s technology for the ultimate challenge. Now available on Android* tablets powered by Intel® Atom™ Processors, users of all ages can access the following:

    1. EvoCreo
      https://appshowcase.intel.com/en-us/android/node/9689

      With the end goal to become an Evoking Master, users will embark on a journey through the world of Zenith, capturing and battling monsters and testing themselves in arenas, working their way up to the coliseum. They’ll combat the sinister plot of the nefarious organization, Shadow Hive, in a completely engrossing epic adventure that’s over 40 hours long. Moves, traits, and abilities can be uniquely combined to suit each player’s strategy, and the multiplayer cross-platform ensures the interactive thread that’s long run through the evolution of video gaming is stronger than ever.

    2. No Hero – Renaissance
      https://appshowcase.intel.com/en-us/android/no-hero-renaissance

      This addictive game cleverly blends charming elements of classic 2D platform games like Prince of Persia, Flashback, and SuperMetroid with current indie games Limbo, Braid, and Rogue Legacy. Players work their way through tough puzzles and deadly traps, navigating obstacles by escaping, running, jumping, and hopefully surviving this unexpected adventure. The target is a young schoolboy named No Hero, who awakens in the bottom of an abyss – an abstract and hostile environment. Lost and afraid, without help from anyone, he tackles the journey of searching for answers.

    3. Battle Empire: Roman Wars
      https://appshowcase.intel.com/en-us/android/battle-empire-roman-wars

      Military defense games are a hallmark of traditional video gaming, a natural sort of progression from the aforementioned Dungeons and Dragons. This app takes the experience a step further; users can build a Roman city that they must develop and defend in order to create a lasting empire. This history simulation game encourages a good strategy on the battlefield to help army unite to win the battles at hand. Players create a strong attacking army to destroy enemies, while expanding their empire and gaining loot from other players.

    So, ready to go to battle? Wanting to challenge your friends? Have a strategy created in your mind to implement? These games have it all covered. Recall the very reasons that first generated interest with video games, and appreciate just how far they’ve come.

    Game’s on! 


    [1] http://www.pong-story.com/intro.htm

    The Total Wellness Equation: 4 Apps that Promote Acuity and Mental Fitness

    $
    0
    0

    Sometimes it seems as if physical fitness gets all of the attention. And while clearly, it is a crucial component of overall wellness, it is actually the full integration of states of physical, mental, and spiritual well-being that truly contribute to our own quality of life.1

    It should go without saying that mental fitness is just as important as physical health, but unfortunately, that’s not always the priority. Mental wellness should never be neglected, and incorporating mental dexterity exercises into your life can help you reap the benefits of a sharper and an overall healthier body for years to come.

    Mental fitness is exactly what it sounds like: keeping your brain in tip-top shape. It’s not like you have to train for the “Brain Olympics” or regularly ace IQ tests, but rather it’s all about activities that help you to decompress, use your true brainpower, and boost memory.

    The effects of technology have made a huge impact on physical fitness – workout machines that can mimic just about any outdoor activity, and devices that track our calories consumed and burned, just to name a few. And luckily, technology is one realm where mental fitness has not been left out; inexpensive, easy-to-access apps create stimulating situations that can truly strengthen your mental acuity.

    Let’s take a look at five apps now available on Android* tablets powered by Intel® Atom™ Processors that can quickly get you in shape when it comes to your mental fitness.

    1. 3D Maze/Labyrinth, by mobadu
      https://appshowcase.intel.com/en-us/android/node/9044

      Suitable for all ages, 3D Maze is an adventure and puzzle game that brings the classic labyrinth genre into a whole new 3D level. Climb to the top of a tower, castle, or pyramid and look down to see the exit point. Check how fast you can reach the end, and at the last labyrinth, you’ll have only 10 minutes before a volcano explodes.

    2. WaveRun, by SoftKiwi
      https://appshowcase.intel.com/en-us/android/waverun

      WaveRun provides an endless, mind-blowing electrical race along parallel wires where you need to survive as long as you can, all while cleverly avoiding obstacles along the way. Challenge friends on unlimited procedurally generated maps, earn achievements, and work up to the top of the leaderboards!

    3. EvoCreo, by Ilmfinity
      https://appshowcase.intel.com/en-us/android/node/9689

      This app sends you on a journey through the world of Zenith, as you take on other Evokers and become a master. This epic adventure provides 40 stimulating hours of gameplay where you customize moves, traits, and abilities to specifically suit your own strategy as you fight the sinister plot of the nefarious organization, Shadow Hive.

    4. City Island 3 – Building Sim, by Sparkling Society
      https://appshowcase.intel.com/en-us/android/city-island-3-building-sim

      Put your mind to work as you create your own story in City Island 3 by unlocking your archipelago with islands, developing your village into a tiny city and then into a large megapolis. High-quality graphics and intuitive gameplay serve up challenging tasks, rewards, and achievements. Fun quests lead to your own virtual paradise during countless hours of thought-provoking gaming fun.

    Just remember: getting to the gym or out on that morning run is only one important aspect of your overall well-being.  Tackling your mental wellness is now easier than ever thanks to these highlighted apps.  Without so much as a drop of sweat, you can instead kick back from just about anywhere, and completely put your mind to the test, feeling the benefits in no time at all.


    [1] https://wellness.ucr.edu/seven_dimensions.html

    Unity* Optimization Guide for Intel x86 Platforms: Part 4

    $
    0
    0

    Contents

    Go Back to Part 3 of the Tutorial:
    Unity* Optimization Guide for Intel x86 Platforms: Part 3


    Editor Optimizations

    Compressing Textures

    Unnecessarily high resolution textures can easily become a bottleneck in mobile games and slower hardware. It is always worth verifying that the textures you use in your scene are in compressed format and that you are selecting the Generate Mip Maps checkbox to enable mip mapping. Mip mapping is similar to the LOD system discussed earlier, but for texture resolutions. If any object you are drawing is super far from the camera, it’s not necessary to use a 1024 x 1024 texture to get the detail, as the object may only be covered by a few pixels.

    Compressing textures and generating mips on the Inspector tab for selected texture
    Figure 44. Compressing textures and generating mips on the Inspector tab for selected texture

    You can verify that your textures are being compressed and mips are being generated by taking a frame capture in GPA and looking at the Texture tab for the draw calls you wish to investigate.  It should be mentioned that generating mip maps can actually result in poorer performance in some cases due to generating additional data.  As always, verify this option in your app.

    Viewing the 4th MIP level and format of the texture in the Frame Analyzer
    Figure 45. Viewing the 4th MIP level and format of the texture in the Frame Analyzer

    Mobile Stock Shaders

    When using stock shaders in your mobile app, it is usually worth switching to the mobile version counterparts provided by Unity to ensure that lower precision floating point values and mobile specific optimizations are being utilized. Try them out in your app by selecting your materials and finding the Mobile section in the drop down menu (Figure 41).

    Stock shaders in Unity
    Figure 46. Stock shaders in Unity

    Static Batching

    Batching combines similarly shaded geometry into single draw calls. This leads to less driver overhead that would normally accompany the extra calls. You can turn on static batching by selecting File->Build Settings>Player Settings and then checking the ‘Static Batching’ option listed.  Unity will now enable these settings by default.

    Static and Dynamic Batching checkboxes under Rendering in Other Settings
    Figure 47 Static and Dynamic Batching checkboxes under Rendering in Other Settings

    Check the static checkboxes for all game objects that will not move. This will allow static batching to be used on multiple similar objects that share a material.

    Batching checkmarks based on object
    Figure 48. Batching checkmarks based on object

    • Make sure you use Renderer.sharedMaterial over Renderer.material to keep material shared.
    • When possible, combine multiple textures used by the same material (Diffuse, Bumped Specular, etc.) into a texture atlas to increase the number of batched objects.

    Most of the time, static batching will provide a tremendous benefit to your application, but there can be situations where it is best not to use it. If you need to lower your memory usage, it can be disadvantageous to use static batching. Even objects that share geometry data will have to pack a copy of each instances vertex / index data into the draw call’s vertex and index buffers. Unity gives an example of when static batching can go wrong with a dense forest scene. In this extreme situation, each tree with the same material is packed into these buffers before issuing the call and that can cause performance issues.

    Dynamic Batching

    Dynamic batching is the same concept as static batching but instead batches draw calls for dynamic objects (objects that move).

    • Dynamic batching is only applied to objects that have less than a total of 900 vertex attributes (subject to change).
    • Objects receiving real-time shadows will not be batched.

    HDR – High Dynamic Range

    If you have a scene with HDR effects like Bloom and Flare using deferred rendering, you will see a large decrease in draw calls by checking the HDR box in the Camera Settings. It’s important to note that each camera has its own HDR checkbox. It’s best to use HDR when using DirectX 10 or better with deferred rendering. HDR is most closely related to the fragment shader. If you wish to use HDR effects, follow these guidelines:

    • Use Deferred Rendering
    • Check the HDR box on each camera with effects requiring HDR (Figure 44)

    HDR option in Camera settings
    Figure 49. HDR option in Camera settings

    Selecting the Optimal Render Path

    Selecting the optimal render path for your app is highly dependent on what you are trying to do. The following is a brief overview of each of the render paths that Unity provides with their pros and cons. Hopefully with this information, you will know which path to choose based on your project specifics, but as with the rest of these optimizations, testing each option is always the way to go! A great way to see which rendering path is optimal for your game is to write a switch in code that will change rendering paths on the push of a button, and then observing the effect of each path in real time via the Unity Profiler and GPA.

    Vertex-Lit Rendering

    Final render target for scene rendered with Vertex-Lit path
    Figure 50. Final render target for scene rendered with Vertex-Lit path

    • Pros
      1. Only does lighting calculations on a per vertex basis, not per-pixel
        • For a model with 1024 vertices that covers the entire full screen window on a 4k monitor, lighting calculations will be done:
          • 1024 times in the per-vertex lighting method
          • 8294400 times in the per-pixel lighting method
      2. Can drastically improve mobile performance
      3. Simple to analyze. Everything done in the base pass.
    • Cons
      1. Real-time shadows and other per-pixel effects not supported
      2. Low quality lighting (Figure ..)

    Vertex-lit rendering path breakdown (all in the base pass)
    Figure 51.Vertex-lit rendering path breakdown (all in the base pass)

    Forward Rendering

    Final render target for scene rendered with Forward path
    Figure 52. Final render target for scene rendered with Forward path

    • Pros
      • Lighting done with a combination of per-pixel, per-vertex, and spherical harmonic techniques
      • Real-time shadows and other per-pixel effects supported
      • Does not incur the memory cost required to build the g-buffer in the deferred path
    • Cons
      • Can lead to many draw calls covering the same pixel(s) if care isn’t taken
    • Pass Breakdown
      • Base pass
        • First per-pixel light reserved for brightest directional light.
        • Next, up to 3 other per-pixel lights that are marked as important are drawn. If no lights are marked as important, the next 3 brightest from the scene are chosen. If there are more lights marked as important that exceed the “per-pixel light count” setting value in Project->Quality, then these are done in additional passes.
        • Next, up to 4 lights are rendered per-vertex.
        • Finally, remaining lights are drawn using spherical harmonic calculations (these values are always calculated, so essentially free on GPU).
      • Per-pixel Lighting Pass
        • An additional pass done for each per-pixel light remaining after the base pass.
      • Semi-transparent Object Pass
        • An additional pass done for semi-transparent objects.

    Final render target for scene rendered with Forward path
    Figure 53. Final render target for scene rendered with Forward path

    Deferred Shading

    Final render target for scene rendered with deferred path
    Figure 54. Final render target for scene rendered with deferred path

    • Pros
      1. Lighting performance is unrelated to scene complexity
      2. Trade heavy lighting computation (FLOPS) for more memory usage leading to a higher chance of being memory bound
      3. Real-time shadows and per-pixel effects supported
    • Cons
      1. Semi-transparent rendering not supported directly. These objects are drawn with an additional forward pass.
      2. Higher memory usage due to building of g-buffer
      3. No support for anti-aliasing
      4. No support for the Mesh Renderer’s Receive Shadows flag
    • Pass Breakdown
      1. G-buffer pass
        • Renders all opaque objects to build the g-buffer.  The layout is as follows:
          • Render Target 0: ARGB32 – Diffuse color in RGB channels and occlusion data in alpha channel
          • Render Target 1: ARGB32 – Specular color in RGB channels and roughness in the alpha channel
          • Render Target 2: ARGB2101010 – World space normal in RGB, and the alpha channel is unused
          • Render Target 3: ARGB32 (non-HDR) or ARGBHalf (HDR) – Emission, lighting, lightmaps, and reflection probes buffer
          • Depth and stencil buffer
      2. Lighting pass
        • Uses the textures generated by the g-buffer pass to do per-pixel lighting calculations. Unity will pass in geometric bounding volumes to Z-test against, making it easy to detect occluded / partially occluded lights.
        • Produces texture with RGB channels holding diffuse lighting values and the alpha channel containing the monochrome specular color.
      3. Light application pass
        • The final pass draws all objects again, using the texture generated by the lighting pass to apply lighting to each object.
      4. Semi-transparent objects pass
        • Require additional forward pass.

    Final render target for scene rendered with deferred path
    Figure 55. Final render target for scene rendered with deferred path

    *More information about the rendering paths available can be found at http://docs.unity3d.com/Manual/Rendering-Tech.html

    Beware Extra Forward Draw Calls

    As previously mentioned, the forward rendering path will issue additional draw calls for each light affecting your geometry up to the “Per-Pixel Light Count” setting shown under the quality settings section of the editor.  Lights marked as important will be used in these calls first, but if there are none marked then Unity will choose the next brightest lights.  In some cases this can lead to a lot of unnecessary overhead, especially when baking your lights is an option. The following screenshots of a GPA capture show the base draw as well as the 3 additional colors.  If there is a need to avoid the following situation, it can be beneficial to bake lights or to lower the per-pixel light count in quality settings.

    GPA Capture showing the 4 draw calls required to paint this floor taking up 55.3% of the scene GPU duration.
    Figure 56. GPA Capture showing the 4 draw calls required to paint this floor taking up 55.3% of the scene GPU duration.

    Viewing color buffers in GPA for additional forward passes required for green, red, and blue lights.
    Figure 57. Viewing color buffers in GPA for additional forward passes required for green, red, and blue lights.

    Android: Splitting Binary

    The latest Unity releases have the ability to produce a Fat Binary or split the binary into separate ARM and x86 portions. You can use the same process to choose either x86 or ARM to test various aspects of a deployment. Evaluating compression, code, and other specifics allows you to troubleshoot or even benchmark your builds. 

    Building FAT APKs does not significantly increase the binary size. You can build slim binaries by simply choosing x86 or ARMv7; however, it would be necessary to maintain two separate builds.

    In Player settings (File>Build Settings > Player Settings):

    1. Open/expand other settings
    2. In Configuration, find Device Filter and choose: FAT (ARMv7+X86). See Figure 51.
      Configuration in Other Settings. Three options shown in Device Filter.
      Figure 58. Configuration in Other Settings. Three options shown in Device Filter.
    3. Choose build (on Build Settings screen) to begin the process of creating the selected binary.

    That’s it! You are now supporting x86 in your Unity Android game deployments.

    A special Unity x86 developer page is available at www.intel.com/software/unity for additional support. 

    Conclusion

    Optimization is a job in and of itself for achieving high levels of performance from your graphic intensive game. Combinations of the above techniques can help you gain significant ground. Using these tools will allow you to dive deeper and make further adjustments.

    Resources

    Reducing textures and sizes: http://docs.unity3d.com/Manual/ReducingFilesize.html

    Shadows: http://docs.unity3d.com/Manual/Shadows.html

    About the Authors

    Cristiano Ferreira is a software engineer working in Intel’s Developer Relations Division with a specialization in games and graphics. Cristiano helps game developers give their customers the best experience possible on Intel hardware.

    Steve Hughes is a Senior Application Engineer with Intel, focusing on support for game development on x86 platforms from desktops and tablets to phones. Prior to Intel, Steve has 12 years of experience as a game developer, working on all aspects of game development for a number of companies.

    Intel® XDK FAQs - App Designer

    $
    0
    0

    Which App Designer framework should I use? Which Intel XDK layout framework is best?

    There is no "best" App Designer framework. Each framework has pros and cons. You should choose that framework which serves your application needs best. The list below provides a quick list of pros and cons for each of the frameworks that are available as part of App Designer.

    • Framework 7 -- PRO: provides pixel perfect layout with device-specific UI elements for Android and iOS platforms. CON: difficult to customize and modify.

    • Twitter Bootstrap 3 -- PRO: a very clean UI framework that relies primarily on CSS with very little JavaScript trickery. Thriving third-party ecosystem with many plugins and add-ons, including themes. CON: some advanced mobile UI mechanisms (like swipe delete) are not part of this framework.

    • App Framework 3 -- PRO: an optimized for mobile library that is very lean. CON: not as widely known as some other UI frameworks.

    • Ionic -- PRO: a very sophisticated mobile framework with many features. If you are familiar with and comfortable with Angular this framework may be a good choice for you. CON: tightly coupled with Angular, many features can only be accessed by writing JavaScript Angular directives. If you are not familiar or comfortable with Angular this is not a good choice!

    • Topcoat -- This UI framework has been deprecated and will be retired from App Designer in a future release of the Intel XDK. You can always use this (or any mobile) framework with the Intel XDK, but you will have to do so manually, without the help of the Intel XDK App Designer UI layout tool. If you wish to continue using Topcoat please visit the Topcoat project page and the Topcoat GitHub repo for documentation.

    • Ratchet -- This UI framework has been deprecated and will be retired from App Designer in a future release of the Intel XDK. You can always use this (or any mobile) framework with the Intel XDK, but you will have to do so manually, without the help of the Intel XDK App Designer UI layout tool. If you wish to continue using Ratchet please visit the Ratchet project page and the Ratchet GitHub repo for documentation.

    • jQuery Mobile -- This UI framework has been deprecated and will be retired from App Designer in a future release of the Intel XDK. You can always use this (or any mobile) framework with the Intel XDK, but you will have to do so manually, without the help of the Intel XDK App Designer UI layout tool. If you wish to continue using jQuery Mobile please visit the jQuery Mobile API page and jQuery Mobile GitHub page for documentation.

    What does the Google* Map widget’s "center type" attribute and its values "Auto calculate,""Address" and "Lat/Long" mean?

    The "center type" parameter defines how the map view is centered in your div. It is used to initialize the map as follows:

    • Lat/Long: center the map on a specific latitude and longitude (that you provide on the properties page)
    • Address: center the map on a specific address (that you provide on the properties page)
    • Auto Calculate: center the map on a collection of markers

    This is just for initialization of the map widget. Beyond that you must use the standard Google maps APIs to move and/or modify the map. See the "google_maps.js" code for initialization of the widget and some calls to the Google maps APIs. There is also a pointer to the Google maps API at the beginning of the JS file.

    To get the current position, you have to use the Geo API, and then push that into the Maps API to display it. The Google Maps API will not give you any device data, it will only display information for you. Please refer to the Intel XDK "Hello, Cordova" sample app for some help with the Geo API. There are a lot of useful comments and console.log messages.

    How do I size UI elements in my project?

    Trying to implement "pixel perfect" user interfaces with HTML5 apps is not recommended as there is a wide array of device resolutions and aspect ratios and it is impossible to insure you are sized properly for every device. Instead, you should use "responsive web design" techniques to build your UI so that it adapts to different sizes automatically. You can also use the CSS media query directive to build CSS rules that are specific to different screen dimensions.

    Note:The viewport is sized in CSS pixels (aka virtual pixels or device independent pixels) and so the physical pixel dimensions are not what you will normally be designing for.

    How do I create lists, buttons and other UI elements with the Intel XDK?

    The Intel XDK provides you with a way to build HTML5 apps that are run in a webview on the target device. This is analogous to running in an embedded browser (refer to this blog for details). Thus, the programming techniques are the same as those you would use inside a browser, when writing a single-page client-side HTML5 app. You can use the Intel XDK App Designer tool to drag and drop UI elements.

    Why is the user interface for Chrome on Android* unresponsive?

    It could be that you are using an outdated version of the App Framework* files. You can find the recent versions here. You can safely replace any App Framework files that App Designer installed in your project with more recent copies as App Designer will not overwrite the new files.

    How do I work with more recent versions of App Framework* since the latest Intel XDK release?

    You can replace the App Framework* files that the Intel XDK automatically inserted with more recent versions that can be found here. App designer will not overwrite your replacement.

    Is there a replacement to XPATH in App Framework* for selecting nodes from an XML document?

    This FAQ applies only to App Framework 2. App Framework 3 no longer includes a replacement for the jQuery selector library, it expects that you are using standard jQuery.

    App Framework is a UI library that implements a subset of the jQuery* selector library. If you wish to use jQuery for XPath manipulation, it is recommend that you use jQuery as your selector library and not App Framework. However, it is also possible to use jQuery with the UI components of App Framework. Please refer to this entry in the App Framework docs.

    It would look similar to this:

    <script src="lib/jq/jquery.js"></script><script src="lib/af/jq.appframework.js"></script><script src="lib/af/appframework.ui.js"></script>

    Why does my App Framework* app that was previously working suddenly start having issues with Android* 4.4?

    Ensure you have upgraded to the latest version of App Framework. If your app was built with the now retired Intel XDK "legacy" build system be sure to set the "Targeted Android Version" to 19 in the Android-Crosswalk build settings. The legacy build targeted Android 4.2.

    How do I manually set a theme?

    If you want to, for example, change the theme only on Android*, you can add the following lines of code:

    1. $.ui.autoLaunch = false; //Stop the App Framework* auto launch right after you load App Framework*
    2. Detect the underlying platform using either navigator.userAgent or intel.xdk.device.platform or window.device.platform. If the platform detected is Android*, set $.ui.useOSThemes=false todisable custom themes and set <div id=”afui” class=”android light”>
    3. Otherwise, set $.ui.useOSThemes=true;
    4. When device ready and document ready have been detected, add $.ui.launch();

    How does page background color work in App Framework?

    In App Framework the BODY is in the background and the page is in the foreground. If you set the background color on the body, you will see the page's background color. If you set the theme to default App Framework uses a native-like theme based on the device at runtime. Otherwise, it uses the App Framework Theme. This is normally done using the following:

    <script>
    $(document).ready(function(){ $.ui.useOSThemes = false; });</script>

    Please see Customizing App Framework UI Skin for additional details.

    Back to FAQs Main

    Intel® XDK FAQs - General

    $
    0
    0

    How can I get started with Intel XDK?

    There are plenty of videos and articles that you can go through here to get started. You could also start with some of our demo apps. It may also help to read Five Useful Tips on Getting Started Building Cordova Mobile Apps with the Intel XDK, which will help you understand some of the differences between developing for a traditional server-based environment and developing for the Intel XDK hybrid Cordova app environment.

    Having prior understanding of how to program using HTML, CSS and JavaScript* is crucial to using the Intel XDK. The Intel XDK is primarily a tool for visualizing, debugging and building an app package for distribution.

    You can do the following to access our demo apps:

    • Select Project tab
    • Select "Start a New Project"
    • Select "Samples and Demos"
    • Create a new project from a demo

    If you have specific questions following that, please post it to our forums.

    Can I use an external editor for development in Intel® XDK?

    Yes, you can open your files and edit them in your favorite editor. However, note that you must use Brackets* to use the "Live Layout Editing" feature. Also, if you are using App Designer (the UI layout tool in Intel XDK) it will make many automatic changes to your index.html file, so it is best not to edit that file externally at the same time you have App Designer open.

    Some popular editors among our users include:

    • Sublime Text* (Refer to this article for information on the Intel XDK plugin for Sublime Text*)
    • Notepad++* for a lighweight editor
    • Jetbrains* editors (Webstorm*)
    • Vim* the editor

    How do I get code refactoring capability in Brackets* (the Intel XDK code editor)?

    ...to be written...

    Why doesn’t my app show up in Google* play for tablets?

    ...to be written...

    What is the global-settings.xdk file and how do I locate it?

    global-settings.xdk contains information about all your projects in the Intel XDK, along with many of the settings related to panels under each tab (Emulate, Debug etc). For example, you can set the emulator to auto-refresh or no-auto-refresh. Modify this file at your own risk and always keep a backup of the original!

    You can locate global-settings.xdk here:

    • Mac OS X*
      ~/Library/Application Support/XDK/global-settings.xdk
    • Microsoft Windows*
      %LocalAppData%\XDK
    • Linux*
      ~/.config/XDK/global-settings.xdk

    If you are having trouble locating this file, you can search for it on your system using something like the following:

    • Windows:
      > cd /
      > dir /s global-settings.xdk
    • Mac and Linux:
      $ sudo find / -name global-settings.xdk

    When do I use the intelxdk.js, xhr.js and cordova.js libraries?

    The intelxdk.js and xhr.js libraries were only required for use with the Intel XDK legacy build tiles (which have been retired). The cordova.js library is needed for all Cordova builds. When building with the Cordova tiles, any references to intelxdk.js and xhr.js libraries in your index.html file are ignored.

    How do I get my Android (and Crosswalk) keystore file?

    Previously you needed to email us, but now you can download your Android (and Crosswalk) keystore file directly. Goto this page https://appcenter.html5tools-software.intel.com/certificate/export.aspx and login (if asked) using your Intel XDK account credentials. You may have to go back to that location a second time after logging in (do this within the same browser tab that you just logged in with to preserve your login credentials).

    If successful, there is a link that, when clicked, will generate a request for an "identification code" for retrieving your keystore. Pushing this link will cause an email to be sent to the email address registered to your account. This email will contain your "identification code" but will call it an "authentication code," different term but same thing. Use this "authentication code" that you received by email to fill in the second form on the web page, above. Filing in that form with the code you received will take you to a new page where you will see:

    • a "Download keystore" link
    • your "key alias"
    • your "keystore password"
    • your "key password"

    Make sure you copy down ALL the information provided! You will need all of that information in order to make use of the keystore. If you lose the password and alias information it will render the key useless!

    If the above fails, please send an email to html5tools@intel.com requesting help. It is important that you send that email from the email address associated with your Intel XDK account.

    How do I rename my project that is a duplicate of an existing project?

    See this FAQ: How do I make a copy of an existing Intel XDK project?

    How do I recover when the Intel XDK hangs or won't start?

    • If you are running Intel XDK on Windows* it must be Windows* 7 or higher. It will not run reliably on earlier versions.
    • Delete the "project-name.xdk" file from the project directory that Intel XDK is trying to open when it starts (it will try to open the project that was open during your last session), then try starting Intel XDK. You will have to "import" your project into Intel XDK again. Importing merely creates the "project-name.xdk" file in your project directory and adds that project to the "global-settings.xdk" file.
    • Rename the project directory Intel XDK is trying to open when it starts. Create a new project based on one of the demo apps. Test Intel XDK using that demo app. If everything works, restart Intel XDK and try it again. If it still works, rename your problem project folder back to its original name and open Intel XDK again (it should now open the sample project you previously opened). You may have to re-select your problem project (Intel XDK should have forgotten that project during the previous session).
    • Clear Intel XDK's program cache directories and files.

      On a Windows machine this can be done using the following on a standard command prompt (administrator is not required):

      > cd %AppData%\..\Local\XDK
      > del *.* /s/q

      To locate the "XDK cache" directory on [OS X*] and [Linux*] systems, do the following:

      $ sudo find / -name global-settings.xdk
      $ cd <dir found above>
      $ sudo rm -rf *

      You might want to save a copy of the "global-settings.xdk" file before you delete that cache directory and copy it back before you restart Intel XDK. Doing so will save you the effort of rebuilding your list of projects. Please refer to this question for information on how to locate the global-settings.xdk file.
    • If you save the "global-settings.xdk" file and restored it in the step above and you're still having hang troubles, try deleting the directories and files above, along with the "global-settings.xdk" file and try it again.
    • Do not store your project directories on a network share (Intel XDK currently has issues with network shares that have not yet been resolved). This includes folders shared between a Virtual machine (VM) guest and its host machine (for example, if you are running Windows* in a VM running on a Mac* host). This network share issue is a known issue with a fix request in place.
    • There have also been issues with running behind a corporate network proxy or firewall. To check them try running Intel XDK from your home network where, presumably, you have a simple NAT router and no proxy or firewall. If things work correctly there then your corporate firewall or proxy may be the source of the problem.
    • Issues with Intel XDK account logins can also cause Intel XDK to hang. To confirm that your login is working correctly, go to the Intel XDK App Center and confirm that you can login with your Intel XDK account. While you are there you might also try deleting the offending project(s) from the App Center.

    If you can reliably reproduce the problem, please send us a copy of the "xdk.log" file that is stored in the same directory as the "global-settings.xdk" file to html5tools@intel.com.

    Is Intel XDK an open source project? How can I contribute to the Intel XDK community?

    No, It is not an open source project. However, it utilizes many open source components that are then assembled into Intel XDK. While you cannot contribute directly to the Intel XDK integration effort, you can contribute to the many open source components that make up Intel XDK.

    The following open source components are the major elements that are being used by Intel XDK:

    • Node-Webkit
    • Chromium
    • Ripple* emulator
    • Brackets* editor
    • Weinre* remote debugger
    • Crosswalk*
    • Cordova*
    • App Framework*

    How do I configure Intel XDK to use 9 patch png for Android* apps splash screen?

    Intel XDK does support the use of 9 patch png for Android* apps splash screen. You can read up more at https://software.intel.com/en-us/xdk/articles/android-splash-screens-using-nine-patch-png on how to create a 9 patch png image and link to an Intel XDK sample using 9 patch png images.

    How do I stop AVG from popping up the "General Behavioral Detection" window when Intel XDK is launched?

    You can try adding nw.exe as the app that needs an exception in AVG.

    What do I specify for "App ID" in Intel XDK under Build Settings?

    Your app ID uniquely identifies your app. For example, it can be used to identify your app within Apple’s application services allowing you to use things like in-app purchasing and push notifications.

    Here are some useful articles on how to create an App ID:

    Is it possible to modify the Android Manifest or iOS plist file with the Intel XDK?

    You cannot modify the AndroidManifest.xml file directly with our build system, as it only exists in the cloud. However, you may do so by creating a dummy plugin that only contains a plugin.xml file containing directives that can be used to add lines to the AndroidManifest.xml file during the build process. In essence, you add lines to the AndroidManifest.xml file via a local plugin.xml file. Here is an example of a plugin that does just that:

    <?xml version="1.0" encoding="UTF-8"?><plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" id="my-custom-intents-plugin" version="1.0.0"><name>My Custom Intents Plugin</name><description>Add Intents to the AndroidManifest.xml</description><license>MIT</license><engines><engine name="cordova" version=">=3.0.0" /></engines><!-- android --><platform name="android"><config-file target="AndroidManifest.xml" parent="/manifest/application"><activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/app_name" android:launchMode="singleTop" android:name="testa" android:theme="@android:style/Theme.Black.NoTitleBar"><intent-filter><action android:name="android.intent.action.SEND" /><category android:name="android.intent.category.DEFAULT" /><data android:mimeType="*/*" /></intent-filter></activity></config-file></platform></plugin>

    You can inspect the AndroidManifest.xml created in an APK, using apktool with the following command line:

    $ apktool d my-app.apk
    $ cd my-app
    $ more AndroidManifest.xml

    This technique exploits the config-file element that is described in the Cordova Plugin Specification docs and can also be used to add lines to iOS plist files. See the Cordova plugin documentation link for additional details.

    Here is an example of such a plugin for modifying the iOS plist file, specifically for adding a BIS key to the plist file:

    <?xml version="1.0" encoding="UTF-8"?><plugin
        xmlns="http://apache.org/cordova/ns/plugins/1.0"
        id="my-custom-bis-plugin"
        version="0.0.2"><name>My Custom BIS Plugin</name><description>Add BIS info to iOS plist file.</description><license>BSD-3</license><preference name="BIS_KEY" /><engines><engine name="cordova" version=">=3.0.0" /></engines><!-- ios --><platform name="ios"><config-file target="*-Info.plist" parent="CFBundleURLTypes"><array><dict><key>ITSAppUsesNonExemptEncryption</key><true/><key>ITSEncryptionExportComplianceCode</key><string>$BIS_KEY</string></dict></array></config-file></platform></plugin>

    How can I share my Intel XDK app build?

    You can send a link to your project via an email invite from your project settings page. However, a login to your account is required to access the file behind the link. Alternatively, you can download the build from the build page, onto your workstation, and push that built image to some location from which you can send a link to that image.

    Why does my iOS build fail when I am able to test it successfully on a device and the emulator?

    Common reasons include:

    • Your App ID specified in the project settings do not match the one you specified in Apple's developer portal.
    • The provisioning profile does not match the cert you uploaded. Double check with Apple's developer site that you are using the correct and current distribution cert and that the provisioning profile is still active. Download the provisioning profile again and add it to your project to confirm.
    • In Project Build Settings, your App Name is invalid. It should be modified to include only alpha, space and numbers.

    How do I add multiple domains in Domain Access?

    Here is the primary doc source for that feature.

    If you need to insert multiple domain references, then you will need to add the extra references in the intelxdk.config.additions.xml file. This StackOverflow entry provides a basic idea and you can see the intelxdk.config.*.xml files that are automatically generated with each build for the <access origin="xxx" /> line that is generated based on what you provide in the "Domain Access" field of the "Build Settings" panel on the Project Tab.

    How do I build more than one app using the same Apple developer account?

    On Apple developer, create a distribution certificate using the "iOS* Certificate Signing Request" key downloaded from Intel XDK Build tab only for the first app. For subsequent apps, reuse the same certificate and import this certificate into the Build tab like you usually would.

    How do I include search and spotlight icons as part of my app?

    Please refer to this article in the Intel XDK documentation. Create anintelxdk.config.additions.xml file in your top level directory (same location as the otherintelxdk.*.config.xml files) and add the following lines for supporting icons in Settings and other areas in iOS*.

    <!-- Spotlight Icon --><icon platform="ios" src="res/ios/icon-40.png" width="40" height="40" /><icon platform="ios" src="res/ios/icon-40@2x.png" width="80" height="80" /><icon platform="ios" src="res/ios/icon-40@3x.png" width="120" height="120" /><!-- iPhone Spotlight and Settings Icon --><icon platform="ios" src="res/ios/icon-small.png" width="29" height="29" /><icon platform="ios" src="res/ios/icon-small@2x.png" width="58" height="58" /><icon platform="ios" src="res/ios/icon-small@3x.png" width="87" height="87" /><!-- iPad Spotlight and Settings Icon --><icon platform="ios" src="res/ios/icon-50.png" width="50" height="50" /><icon platform="ios" src="res/ios/icon-50@2x.png" width="100" height="100" />

    For more information related to these configurations, visit http://cordova.apache.org/docs/en/3.5.0/config_ref_images.md.html#Icons%20and%20Splash%20Screens.

    For accurate information related to iOS icon sizes, visit https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/IconMatrix.html

    NOTE: The iPhone 6 icons will only be available if iOS* 7 or 8 is the target.

    Cordova iOS* 8 support JIRA tracker: https://issues.apache.org/jira/browse/CB-7043

    Does Intel XDK support Modbus TCP communication?

    No, since Modbus is a specialized protocol, you need to write either some JavaScript* or native code (in the form of a plugin) to handle the Modbus transactions and protocol.

    How do I sign an Android* app using an existing keystore?

    Uploading an existing keystore in Intel XDK is not currently supported but you can send an email to html5tools@intel.com with this request. We can assist you there.

    How do I build separately for different Android* versions?

    Under the Projects Panel, you can select the Target Android* version under the Build Settings collapsible panel. You can change this value and build your application multiple times to create numerous versions of your application that are targeted for multiple versions of Android*.

    How do I display the 'Build App Now' button if my display language is not English?

    If your display language is not English and the 'Build App Now' button is proving to be troublesome, you may change your display language to English which can be downloaded by a Windows* update. Once you have installed the English language, proceed to Control Panel > Clock, Language and Region > Region and Language > Change Display Language.

    How do I update my Intel XDK version?

    When an Intel XDK update is available, an Update Version dialog box lets you download the update. After the download completes, a similar dialog lets you install it. If you did not download or install an update when prompted (or on older versions), click the package icon next to the orange (?) icon in the upper-right to download or install the update. The installation removes the previous Intel XDK version.

    How do I import my existing HTML5 app into the Intel XDK?

    If your project contains an Intel XDK project file (<project-name>.xdk) you should use the "Open an Intel XDK Project" option located at the bottom of the Projects List on the Projects tab (lower left of the screen, round green "eject" icon, on the Projects tab). This would be the case if you copied an existing Intel XDK project from another system or used a tool that exported a complete Intel XDK project.

    If your project does not contain an Intel XDK project file (<project-name>.xdk) you must "import" your code into a new Intel XDK project. To import your project, use the "Start a New Project" option located at the bottom of the Projects List on the Projects tab (lower left of the screen, round blue "plus" icon, on theProjects tab). This will open the "Samples, Demos and Templates" page, which includes an option to "Import Your HTML5 Code Base." Point to the root directory of your project. The Intel XDK will attempt to locate a file named index.html in your project and will set the "Source Directory" on the Projects tab to point to the directory that contains this file.

    If your imported project did not contain an index.html file, your project may be unstable. In that case, it is best to delete the imported project from the Intel XDK Projects tab ("x" icon in the upper right corner of the screen), rename your "root" or "main" html file to index.html and import the project again. Several components in the Intel XDK depend on this assumption that the main HTML file in your project is named index.hmtl. See Introducing Intel® XDK Development Tools for more details.

    It is highly recommended that your "source directory" be located as a sub-directory inside your "project directory." This insures that non-source files are not included as part of your build package when building your application. If the "source directory" and "project directory" are the same it results in longer upload times to the build server and unnecessarily large application executable files returned by the build system. See the following images for the recommended project file layout.

    I am unable to login to App Preview with my Intel XDK password.

    On some devices you may have trouble entering your Intel XDK login password directly on the device in the App Preview login screen. In particular, sometimes you may have trouble with the first one or two letters getting lost when entering your password.

    Try the following if you are having such difficulties:

    • Reset your password, using the Intel XDK, to something short and simple.

    • Confirm that this new short and simple password works with the XDK (logout and login to the Intel XDK).

    • Confirm that this new password works with the Intel Developer Zone login.

    • Make sure you have the most recent version of Intel App Preview installed on your devices. Go to the store on each device to confirm you have the most recent copy of App Preview installed.

    • Try logging into Intel App Preview on each device with this short and simple password. Check the "show password" box so you can see your password as you type it.

    If the above works, it confirms that you can log into your Intel XDK account from App Preview (because App Preview and the Intel XDK go to the same place to authenticate your login). When the above works, you can go back to the Intel XDK and reset your password to something else, if you do not like the short and simple password you used for the test.

    How do I completely uninstall the Intel XDK from my system?

    Take the following steps to completely uninstall the XDK from your Windows system:

    • From the Windows Control Panel, remove the Intel XDK, using the Windows uninstall tool.

    • Then:
      > cd %LocalAppData%\Intel\XDK
      > del *.* /s/q

    • Then:
      > cd %LocalAppData%\XDK
      > copy global-settings.xdk %UserProfile%
      > del *.* /s/q
      > copy %UserProfile%\global-settings.xdk .

    • Then:
      -- Goto xdk.intel.com and select the download link.
      -- Download and install the new XDK.

    To do the same on a Linux or Mac system:

    • On a Linux machine, run the uninstall script, typically /opt/intel/XDK/uninstall.sh.
       
    • Remove the directory into which the Intel XDK was installed.
      -- Typically /opt/intel or your home (~) directory on a Linux machine.
      -- Typically in the /Applications/Intel XDK.app directory on a Mac.
       
    • Then:
      $ find ~ -name global-settings.xdk
      $ cd <result-from-above> (for example ~/Library/Application Support/XDK/ on a Mac)
      $ cp global-settings.xdk ~
      $ rm -Rf *
      $ mv ~/global-settings.xdk .

       
    • Then:
      -- Goto xdk.intel.com and select the download link.
      -- Download and install the new XDK.

    Is there a tool that can help me highlight syntax issues in Intel XDK?

    Yes, you can use the various linting tools that can be added to the Brackets editor to review any syntax issues in your HTML, CSS and JS files. Go to the "File > Extension Manager..." menu item and add the following extensions: JSHint, CSSLint, HTMLHint, XLint for Intel XDK. Then, review your source files by monitoring the small yellow triangle at the bottom of the edit window (a green check mark indicates no issues).

    How do I delete built apps and test apps from the Intel XDK build servers?

    You can manage them by logging into: https://appcenter.html5tools-software.intel.com/csd/controlpanel.aspx. This functionality will eventually be available within Intel XDK after which access to app center will be removed.

    I need help with the App Security API plugin; where do I find it?

    Visit the primary documentation book for the App Security API and see this forum post for some additional details.

    When I install my app or use the Debug tab Avast antivirus flags a possible virus, why?

    If you are receiving a "Suspicious file detected - APK:CloudRep [Susp]" message from Avast anti-virus installed on your Android device it is due to the fact that you are side-loading the app (or the Intel XDK Debug modules) onto your device (using a download link after building or by using the Debug tab to debug your app), or your app has been installed from an "untrusted" Android store. See the following official explanation from Avast:

    Your application was flagged by our cloud reputation system. "Cloud rep" is a new feature of Avast Mobile Security, which flags apks when the following conditions are met:

    1. The file is not prevalent enough; meaning not enough users of Avast Mobile Security have installed your APK.
    2. The source is not an established market (Google Play is an example of an established market).

    If you distribute your app using Google Play (or any other trusted market) your users should not see any warning from Avast.

    Following are some of the Avast anti-virus notification screens you might see on your device. All of these are perfectly normal, they are due to the fact that you must enable the installation of "non-market" apps in order to use your device for debug and the App IDs associated with your never published app or the custom debug modules that the Debug tab in the Intel XDK builds and installs on your device will not be found in a "established" (aka "trusted") market, such as Google Play.

    If you choose to ignore the "Suspicious app activity!" threat you will not receive a threat for that debug module any longer. It will show up in the Avast 'ignored issues' list. Updates to an existing, ignored, custom debug module should continue to be ignored by Avast. However, new custom debug modules (due to a new project App ID or a new version of Crosswalk selected in your project's Build Settings) will result in a new warning from the Avast anti-virus tool.

      

      

    How do I add a Brackets extension to the editor that is part of the Intel XDK?

    The number of Brackets extensions that are provided in the built-in edition of the Brackets editor are limited to insure stability of the Intel XDK product. Not all extensions are compatible with the edition of Brackets that is embedded within the Intel XDK. Adding incompatible extensions can cause the Intel XDK to quit working.

    Despite this warning, there are useful extensions that have not been included in the editor and which can be added to the Intel XDK. Adding them is temporary, each time you update the Intel XDK (or if you reinstall the Intel XDK) you will have to "re-add" your Brackets extension. To add a Brackets extension, use the following procedure:

    • exit the Intel XDK
    • download a ZIP file of the extension you wish to add
    • on Windows, unzip the extension here:
      %LocalAppData%\Intel\XDK\xdk\brackets\b\extensions\dev
    • on Mac OS X, unzip the extension here:
      /Applications/Intel\ XDK.app/Contents/Resources/app.nw/brackets/b/extensions/dev
    • start the Intel XDK

    Note that the locations given above are subject to change with new releases of the Intel XDK.

    Why does my app or game require so many permissions on Android when built with the Intel XDK?

    When you build your HTML5 app using the Intel XDK for Android or Android-Crosswalk you are creating a Cordova app. It may seem like you're not building a Cordova app, but you are. In order to package your app so it can be distributed via an Android store and installed on an Android device, it needs to be built as a hybrid app. The Intel XDK uses Cordova to create that hybrid app.

    A pure Cordova app requires the NETWORK permission, it's needed to "jump" between your HTML5 environment and the native Android environment. Additional permissions will be added by any Cordova plugins you include with your application; which permissions are includes are a function of what that plugin does and requires.

    Crosswalk for Android builds also require the NETWORK permission, because the Crosswalk image built by the Intel XDK includes support for Cordova. In addition, current versions of Crosswalk (12 and 14 at the time this FAQ was written)also require NETWORK STATE and WIFI STATE. There is an extra permission in some versions of Crosswalk (WRITE EXTERNAL STORAGE) that is only needed by the shared model library of Crosswalk, we have asked the Crosswalk project to remove this permission in a future Crosswalk version.

    If you are seeing more than the following five permissions in your XDK-built Crosswalk app:

    • android.permission.INTERNET
    • android.permission.ACCESS_NETWORK_STATE
    • android.permission.ACCESS_WIFI_STATE
    • android.permission.INTERNET
    • android.permission.WRITE_EXTERNAL_STORAGE

    then you are seeing permissions that have been added by some plugins. Each plugin is different, so there is no hard rule of thumb. The two "default" core Cordova plugins that are added by the Intel XDK blank templates (device and splash screen) do not require any Android permissions.

    BTW: the permission list above comes from a Crosswalk 14 build. Crosswalk 12 builds do not included the last permission; it was added when the Crosswalk project introduced the shared model library option, which started with Crosswalk 13 (the Intel XDK does not support 13 builds).

    How do I make a copy of an existing Intel XDK project?

    If you just need to make a backup copy of an existing project, and do not plan to open that backup copy as a project in the Intel XDK, do the following:

    • Exit the Intel XDK.
    • Copy the entire project directory:
      • on Windows, use File Explorer to "right-click" and "copy" your project directory, then "right-click" and "paste"
      • on Mac use Finder to "right-click" and then "duplicate" your project directory
      • on Linux, open a terminal window, "cd" to the folder that contains your project, and type "cp -a old-project/ new-project/" at the terminal prompt (where "old-project/" is the folder name of your existing project that you want to copy and "new-project/" is the name of the new folder that will contain a copy of your existing project)

    If you want to use an existing project as the starting point of a new project in the Intel XDK. The process described below will insure that the build system does not confuse the ID in your old project with that stored in your new project. If you do not follow the procedure below you will have multiple projects using the same project ID (a special GUID that is stored inside the Intel XDK <project-name>.xdk file in the root directory of your project). Each project in your account must have a unique project ID.

    • Exit the Intel XDK.
    • Make a copy of your existing project using the process described above.
    • Inside the new project that you made (that is, your new copy of your old project), make copies of the <project-name>.xdk file and <project-name>.xdke files and rename those copies to something like project-new.xdk and project-new.xdke (anything you like, just something different than the original project name, preferably the same name as the new project folder in which you are making this new project).
    • Using a TEXT EDITOR (only) (such as Notepad or Sublime or Brackets or some other TEXT editor), open your new "project-new.xdk" file (whatever you named it) and find the projectGuid line, it will look something like this:
      "projectGuid": "a863c382-ca05-4aa4-8601-375f9f209b67",
    • Change the "GUID" to all zeroes, like this: "00000000-0000-0000-000000000000"
    • Save the modified "project-new.xdk" file.
    • Open the Intel XDK.
    • Goto the Projects tab.
    • Select "Open an Intel XDK Project" (the green button at the bottom left of the Projects tab).
    • To open this new project, locate the new "project-new.xdk" file inside the new project folder you copied above.
    • Don't forget to change the App ID in your new project. This is necessary to avoid conflicts with the project you copied from, in the store and when side-loading onto a device.

    My project does not include a www folder. How do I fix it so it includes a www or source directory?

    The Intel XDK HTML5 and Cordova project file structures are meant to mimic a standard Cordova project. In a Cordova (or PhoneGap) project there is a subdirectory (or folder) named www that contains all of the HTML5 source code and asset files that make up your application. For best results, it is advised that you follow this convention, of putting your source inside a "source directory" inside of your project folder.

    This most commonly happens as the result of exporting a project from an external tool, such as Construct2, or as the result of importing an existing HTML5 web app that you are converting into a hybrid mobile application (eg., an Intel XDK Corodova app). If you would like to convert an existing Intel XDK project into this format, follow the steps below:

    • Exit the Intel XDK.
    • Copy the entire project directory:
      • on Windows, use File Explorer to "right-click" and "copy" your project directory, then "right-click" and "paste"
      • on Mac use Finder to "right-click" and then "duplicate" your project directory
      • on Linux, open a terminal window, "cd" to the folder that contains your project, and type "cp -a old-project/ new-project/" at the terminal prompt (where "old-project/" is the folder name of your existing project that you want to copy and "new-project/" is the name of the new folder that will contain a copy of your existing project)
    • Create a "www" directory inside the new duplicate project you just created above.
    • Move your index.html and other source and asset files to the "www" directory you just created -- this is now your "source" directory, located inside your "project" directory (do not move the <project-name>.xdk and xdke files and any intelxdk.config.*.xml files, those must stay in the root of the project directory)
    • Inside the new project that you made above (by making a copy of the old project), rename the <project-name>.xdk file and <project-name>.xdke files to something like project-copy.xdk and project-copy.xdke (anything you like, just something different than the original project, preferably the same name as the new project folder in which you are making this new project).
    • Using a TEXT EDITOR (only) (such as Notepad or Sublime or Brackets or some other TEXT editor), open the new "project-copy.xdk" file (whatever you named it) and find the line named projectGuid, it will look something like this:
      "projectGuid": "a863c382-ca05-4aa4-8601-375f9f209b67",
    • Change the "GUID" to all zeroes, like this: "00000000-0000-0000-000000000000"
    • A few lines down find: "sourceDirectory": "",
    • Change it to this: "sourceDirectory": "www",
    • Save the modified "project-copy.xdk" file.
    • Open the Intel XDK.
    • Goto the Projects tab.
    • Select "Open an Intel XDK Project" (the green button at the bottom left of the Projects tab).
    • To open this new project, locate the new "project-copy.xdk" file inside the new project folder you copied above.

    Can I install more than one copy of the Intel XDK onto my development system?

    Yes, you can install more than one version onto your development system. However, you cannot run multiple instances of the Intel XDK at the same time. Be aware that new releases sometimes change the project file format, so it is a good idea, in these cases, to make a copy of your project if you need to experiment with a different version of the Intel XDK. See the instructions in a FAQ entry above regarding how to make a copy of your Intel XDK project.

    Follow the instructions in this forum post to install more than one copy of the Intel XDK onto your development system.

    On Apple OS X* and Linux* systems, does the Intel XDK need the OpenSSL* library installed?

    Yes. Several features of the Intel XDK require the OpenSSL library, which typically comes pre-installed on Linux and OS X systems. If the Intel XDK reports that it could not find libssl, go to https://www.openssl.org to download and install it.

    I have a web application that I would like to distribute in app stores without major modifications. Is this possible using the Intel XDK?

    Yes, if you have a true web app or “client app” that only uses HTML, CSS and JavaScript, it is usually not too difficult to convert it to a Cordova hybrid application (this is what the Intel XDK builds when you create an HTML5 app). If you rely heavily on PHP or other server scripting languages embedded in your pages you will have more work to do. Because your Cordova app is not associated with a server, you cannot rely on server-based programming techniques; instead, you must rewrite any such code to user RESTful APIs that your app interacts with using, for example, AJAX calls.

    What is the best training approach to using the Intel XDK for a newbie?

    First, become well-versed in the art of client web apps, apps that rely only on HTML, CSS and JavaScript and utilize RESTful APIs to talk to network services. With that you will have mastered 80% of the problem. After that, it is simply a matter of understanding how Cordova plugins are able to extend the JavaScript API for access to features of the platform. For HTML5 training there are many sites providing tutorials. It may also help to read Five Useful Tips on Getting Started Building Cordova Mobile Apps with the Intel XDK, which will help you understand some of the differences between developing for a traditional server-based environment and developing for the Intel XDK hybrid Cordova app environment.

    What is the best platform to start building an app with the Intel XDK? And what are the important differences between the Android, iOS and other mobile platforms?

    There is no one most important difference between the Android, iOS and other platforms. It is important to understand that the HTML5 runtime engine that executes your app on each platform will vary as a function of the platform. Just as there are differences between Chrome and Firefox and Safari and Internet Explorer, there are differences between iOS 9 and iOS 8 and Android 4 and Android 5, etc. Android has the most significant differences between vendors and versions of Android. This is one of the reasons the Intel XDK offers the Crosswalk for Android build option, to normalize and update the Android issues.

    In general, if you can get your app working well on Android (or Crosswalk for Android) first you will generally have fewer issues to deal with when you start to work on the iOS and Windows platforms. In addition, the Android platform has the most flexible and useful debug options available, so it is the easiest platform to use for debugging and testing your app.

    Is my password encrypted and why is it limited to fifteen characters?

    Yes, your password is stored encrypted and is managed by https://signin.intel.com. Your Intel XDK userid and password can also be used to log into the Intel XDK forum as well as the Intel Developer Zone. the Intel XDK does not store nor does it manage your userid and password.

    The rules regarding allowed userids and passwords are answered on this Sign In FAQ page, where you can also find help on recovering and changing your password.

    Why does the Intel XDK take a long time to start on Linux or Mac?

    ...and why am I getting this error message? "Attempt to contact authentication server is taking a long time. You can wait, or check your network connection and try again."

    At startup, the Intel XDK attempts to automatically determine the proxy settings for your machine. Unfortunately, on some system configurations it is unable to reliably detect your system proxy settings. As an example, you might see something like this image when starting the Intel XDK.

    On some systems you can get around this problem by setting some proxy environment variables and then starting the Intel XDK from a command-line that includes those configured environment variables. To set those environment variables, similar to the following:

    $ export no_proxy="localhost,127.0.0.1/8,::1"
    $ export NO_PROXY="localhost,127.0.0.1/8,::1"
    $ export http_proxy=http://proxy.mydomain.com:123/
    $ export HTTP_PROXY=http://proxy.mydomain.com:123/
    $ export https_proxy=http://proxy.mydomain.com:123/
    $ export HTTPS_PROXY=http://proxy.mydomain.com:123/

    IMPORTANT! The name of your proxy server and the port (or ports) that your proxy server requires will be different than those shown in the example above. Please consult with your IT department to find out what values are appropriate for your site. Intel has no way of knowing what configuration is appropriate for your network.

    If you use the Intel XDK in multiple locations (at work and at home), you may have to change the proxy settings before starting the Intel XDK after switching to a new network location. For example, many work networks use a proxy server, but most home networks do not require such a configuration. In that case, you need to be sure to "unset" the proxy environment variables before starting the Intel XDK on a non-proxy network.

    After you have successfully configured your proxy environment variables, you can start the Intel XDK manually, from the command-line.

    On a Mac, where the Intel XDK is installed in the default location, type the following (from a terminal window that has the above environment variables set):

    $ open /Applications/Intel\ XDK.app/

    On a Linux machine, assuming the Intel XDK has been installed in the ~/intel/XDK directory, type the following (from a terminal window that has the above environment variables set):

    $ ~/intel/XDK/xdk.sh &

    In the Linux case, you will need to adjust the directory name that points to the xdk.sh file in order to start. The example above assumes a local install into the ~/intel/XDK directory. Since Linux installations have more options regarding the installation directory, you will need to adjust the above to suit your particular system and install directory.

    How do I generate a P12 file on a Windows machine?

    See these articles:

    How do I change the default dir for creating new projects in the Intel XDK?

    You can change the default new project location manually by modifying a field in the global-settings.xdk file. Locate the global-settings.xdk file on your system (the precise location varies as a function of the OS) and find this JSON object inside that file:

    "projects-tab": {"defaultPath": "/Users/paul/Documents/XDK","LastSortType": "descending|Name","lastSortType": "descending|Opened","thirdPartyDisclaimerAcked": true
      },

    The example above came from a Mac. On a Mac the global-settings.xdk file is located in the "~/Library/Application Support/XDK" directory.

    On a Windows machine the global-settings.xdk file is normally found in the "%LocalAppData%\XDK" directory. The part you are looking for will look something like this:

    "projects-tab": {"thirdPartyDisclaimerAcked": false,"LastSortType": "descending|Name","lastSortType": "descending|Opened","defaultPath": "C:\\Users\\paul/Documents"
      },

    Obviously, it's the defaultPath part you want to change.

    BE CAREFUL WHEN YOU EDIT THE GLOBAL-SETTINGS.XDK FILE!! You've been warned...

    Make sure the result is proper JSON when you are done, or it may cause your XDK to cough and hack loudly. Make a backup copy of global-settings.xdk before you start, just in case.

    Where I can find recent and upcoming webinars list?

    Back to FAQs Main

    Intel® XDK FAQs - Crosswalk

    $
    0
    0

    How do I play audio with different playback rates?

    Here is a code snippet that allows you to specify playback rate:

    var myAudio = new Audio('/path/to/audio.mp3');
    myAudio.play();
    myAudio.playbackRate = 1.5;

    Why are Intel XDK Android Crosswalk build files so large?

    When your app is built with Crosswalk it will be a minimum of 15-18MB in size because it includes a complete web browser (the Crosswalk runtime or webview) for rendering your app instead of the built-in webview on the device. Despite the additional size, this is the preferred solution for Android, because the built-in webviews on the majority of Android devices are inconsistent and poorly performing.

    See these articles for more information:

    Why is the size of my installed app much larger than the apk for a Crosswalk application?

    This is because the apk is a compressed image, so when installed it occupies more space due to being decompressed. Also, when your Crosswalk app starts running on your device it will create some data files for caching purposes which will increase the installed size of the application.

    Why does my Android Crosswalk build fail with the com.google.playservices plugin?

    The Intel XDK Crosswalk build system used with CLI 4.1.2 Crosswalk builds does not support the library project format that was introduced in the "com.google.playservices@21.0.0" plugin. Use "com.google.playservices@19.0.0" instead.

    Why does my app fail to run on some devices?

    There are some Android devices in which the GPU hardware/software subsystem does not work properly. This is typically due to poor design or improper validation by the manufacturer of that Android device. Your problem Android device probably falls under this category.

    How do I stop "pull to refresh" from resetting and restarting my Crosswalk app?

    See the code posted in this forum thread for a solution: /en-us/forums/topic/557191#comment-1827376.

    An alternate solution is to add the following lines to your intelxdk.config.additions.xml file:

    <!-- disable reset on vertical swipe down --><intelxdk:crosswalk xwalk-command-line="--disable-pull-to-refresh-effect" />

    Which versions of Crosswalk are supported and why do you not support version X, Y or Z?

    The specific versions of Crosswalk that are offered via the Intel XDK are based on what the Crosswalk project releases and the timing of those releases relative to Intel XDK build system updates. This is one of the reasons you do not see every version of Crosswalk supported by our Android-Crosswalk build system.

    With the September, 2015 release of the Intel XDK, the method used to build embedded Android-Crosswalk versions changed to the "pluggable" webview Cordova build system. This new build system was implemented with the help of the Cordova project and became available with their release of the Android Cordova 4.0 framework (coincident with their Cordova CLI 5 release). With this change to the Android Cordova framework and the Cordova CLI build system, we can now more quickly adapt to new version releases of the Crosswalk project. Support for previous Crosswalk releases required updating a special build system that was forked from the Cordova Android project. This new "pluggable" webview build system means that the build system can now use the standard Cordova build system, because it now includes the Crosswalk library as a "pluggable" component.

    The "old" method of building Android-Crosswalk APKs relied on a "forked" version of the Cordova Android framework, and is based on the Cordova Android 3.6.3 framework and is used when you select CLI 4.1.2 in the Project tab's build settings page. Only Crosswalk versions 7, 10, 11, 12 and 14 are supported by the Intel XDK when using this build setting.

    Selecting CLI 5.1.1 in the build settings will generate a "pluggable" webview built app. A "pluggable" webview app (built with CLI 5.1.1) results in an app built with the Cordova Android 4.1.0 framework. As of the latest update to this FAQ, the CLI 5.1.1 build system supported Crosswalk 15. Future releases of the Intel XDK and the build system will support higher versions of Crosswalk and the Cordova Android framework.

    In both cases, above, the net result (when performing an "embedded" build) will be two processor architecture-specific APKs: one for use on an x86 device and one for use on an ARM device. The version codes of those APKs are modified to insure that both can be uploaded to the Android store under the same app name, insuring that the appropriate APK is automatically delivered to the matching device (i.e., the x86 APK is delivered to Intel-based Android devices and the ARM APK is delivered to ARM-based Android devices).

    For more information regarding Crosswalk and the Intel XDK, please review these documents:

    How do I prevent my Crosswalk app from auto-completing passwords?

    Use the Ionic Keyboard plugin and set the spellcheck attribute to false.

    How can I improve the performance of my Crosswalk app so it is as fast as Crosswalk 7 was?

    Beginning with the Intel XDK CLI 5.1.1 build system you must add the --ignore-gpu-blacklist option to your intelxdk.config.additions.xml file if you want the additional performance this option provides to blacklisted devices. See this forum post for additional details.

    Also, you can experiment with the CrosswalkAnimatable option in your intelxdk.config.additions.xml file (details regarding the CrosswalkAnimatable option are available in this Crosswalk Project wiki post: Android SurfaceView vs TextureView).

    <!-- Controls configuration of Crosswalk-Android "SurfaceView" or "TextureView" --><!-- Default is SurfaceView if >= CW15 and TextureView if <= CW14 --><!-- Option can only be used with Intel XDK CLI5+ build systems --><!-- SurfaceView is preferred, TextureView should only be used in special cases --><!-- Enable Crosswalk-Android TextureView by setting this option to true --><preference name="CrosswalkAnimatable" value="false" />

    See Chromium Command-Line Options for Crosswalk Builds with the Intel XDK for some additional tools that can be used to modify the Crosswalk's webview runtime parameters, especially the --ignore-gpu-blacklist option.

    Why does the Google store refuse to publish my Crosswalk app?

    For full details, please read Android and Crosswalk Cordova Version Code Issues. For a summary, read this FAQ.

    There is a change to the version code handling by the Crosswalk and Android build systems based on Cordova CLI 5.0 and later. This change was implemented by the Apache Cordova project. This new version of Cordova CLI automatically modifies the android:versionCode when building for Crosswalk and Android. Because our CLI 5.1.1 build system is now more compatible with standard Cordova CLI, this change results in a discrepancy in the way your android:versionCode is handled when building for Crosswalk (15) or Android with CLI 5.1.1 when compared to building with CLI 4.1.2.

    If you have never published an app to an Android store this change will have little or no impact on you. This change might affect attempts to side-load an app onto a device, in which case the simplest solution is to uninstall the previously side-loaded app before installing the new app.

    Here's what Cordova CLI 5.1.1 (Cordova-Android 4.x) is doing with the android:versionCode number (which you specify in the App Version Code field within the Build Settings section of the Projects tab):

    Cordova-Android 4.x (Intel XDK CLI 5.1.1 for Crosswalk or Android builds) does this:

    • multiplies your android:versionCode by 10

    then, if you are doing a Crosswalk (15) build:

    • adds 2 to the android:versionCode for ARM builds
    • adds 4 to the android:versionCode for x86 builds

    otherwise, if you are performing a standard Android build (non-Crosswalk):

    • adds 0 to the android:versionCode if the Minimum Android API is < 14
    • adds 8 to the android:versionCode if the Minimum Android API is 14-19
    • adds 9 to the android:versionCode if the Minimum Android API is > 19 (i.e., >= 20)

    If you HAVE PUBLISHED a Crosswalk app to an Android store this change may impact your ability to publish a newer version of your app! In that case, if you are building for Crosswalk, add 6000 (six with three zeroes) to your existing App Version Code field in the Crosswalk Build Settings section of the Projects tab. If you have only published standard Android apps in the past and are still publishing only standard Android apps you should not have to make any changes to the App Version Code field in the Android Builds Settings section of the Projects tab.

    The workaround described above only applies to Crosswalk CLI 5.1.1 and later builds!

    When you build a Crosswalk app with CLI 4.1.2 (which uses Cordova-Android 3.6) you will get the old Intel XDK behavior where: 60000 and 20000 (six with four zeros and two with four zeroes) are added to the android:versionCode for Crosswalk builds and no change is made to the android:versionCode for standard Android builds.

    NOTE:

    • Android API 14 corresponds to Android 4.0
    • Android API 19 corresponds to Android 4.4
    • Android API 20 corresponds to Android 5.0
    • CLI 5.1.1 (Cordova-Android 4.x) does not allow building for Android 2.x or Android 3.x

    Why is my Crosswalk app generating errno 12 Out of memory errors on some devices?

    If you are using the WebGL 2D canvas APIs and your app crashes on some devices because you added the --ignore-gpu-blacklist flag to your intelxdk.config.additions.xml file, you may need to also add the --disable-accelerated-2d-canvas flag. Using the --ignore-gpu-blacklist flag enables the use of the GPU in some problem devices, but can then result in problems with some GPUs that are not blacklisted. The --disable-accelerated-2d-canvas flag allows those non-blacklisted devices to operate properly in the presence of WebGL 2D canvas APIs and the --ignore-gpu-blacklist flag.

    You likely have this problem if your app crashes after running a few seconds with the an error like the following:

    <gsl_ldd_control:364>: ioctl fd 46 code 0xc00c092f (IOCTL_KGSL_GPMEM_ALLOC) failed: errno 12 Out of memory <ioctl_kgsl_sharedmem_alloc:1176>: ioctl_kgsl_sharedmem_alloc: FATAL ERROR : (null).

    See Chromium Command-Line Options for Crosswalk Builds with the Intel XDK for additional info regarding the --ignore-gpu-blacklist flag and other Chromium option flags.

    Construct2 Tutorial: How to use AdMob and IAP plugins with Crosswalk and the Intel XDK.

    See this tutorial on the Scirra tutorials site: How to use AdMob and IAP official plugins on Android-Crosswalk/XDK written by Construct2 developer Kyatric.

    Back to FAQs Main


    Intel® VTune™ Amplifier Tutorials

    $
    0
    0

    The following tutorials are quick paths to start using the Intel® VTune™ Amplifier. Each demonstrates an end-to-end workflow you can ultimately apply to your own applications.

    NOTE:

    Apart from the analysis and target configuration details, most of the VTune Amplifier XE tutorials are also applicable to the VTune Amplifier for Systems. The Finding Hotspots on the Intel Xeon Phi coprocessor tutorial is applicable only to the VTune Amplifier XE.

    VTune Amplifier XE Tutorials

    Take This Short TutorialLearn To Do This

    Finding Hotspots
    Duration: 10-15 minutes

    C++ Tutorial
    Windows* OS: HTML | PDF
    Linux* OS: HTML | PDF
    Sample code: tachyon_vtune_amp_xe

    Fortran Tutorial
    Windows* OS: HTML | PDF
    Linux* OS: HTML | PDF
    Sample code: nqueens_fortran

    Identify where your application is spending time, detect the most time-consuming program units and how they were called.

    Finding Hotspots on the Intel® Xeon Phi™ Coprocessor
    Duration: 10-15 minutes

    C++ Tutorial
    Windows* OS: HTML | PDF
    Linux* OS: HTML | PDF
    Sample code: matrix_vtune_amp_xe

    Identify where your native Intel Xeon Phi coprocessor-based application is spending time, estimate code efficiency by analyzing hardware event-based metrics.

    Analyzing Locks and Waits
    Duration: 10-15 minutes

    C++ Tutorial
    Windows* OS: HTML | PDF
    Linux* OS: HTML | PDF
    Sample code: tachyon_vtune_amp_xe

    Identify locks and waits preventing parallelization.

    Identifying Hardware Issues
    Duration: 10-15 minutes

    C++ Tutorial
    Windows* OS: HTML | PDF
    Linux* OS: HTML | PDF
    Sample code: matrix_vtune_amp_xe

    Identify the hardware-related issues in your application such as data sharing, cache misses, branch misprediction, and others.

    VTune Amplifier for Systems Tutorials

    Take This Short TutorialLearn To Do This

    Finding Hotspots on a Remote Linux* System
    Duration: 10-15 minutes

    C++ Tutorial
    Linux* OS: HTML | PDF
    Sample code: tachyon_vtune_amp_xe

    Configure and run a remote Advanced Hotspots analysis on a Linux target system.

    Finding Hotspots on an Android* Platform
    Duration: 10-15 minutes

    C++ Tutorial
    Windows* OS: HTML | PDF
    Linux* OS: HTML | PDF
    Sample code: tachyon_vtune_amp_xe

    Configure and run a remote Basic Hotspots analysis on an Android target system.

    Analyzing Energy Usage on an Android* Platform
    Duration: 10-15 minutes

    Tutorial
    Linux* OS: HTML | PDF
    Windows* OS: HTML | PDF

    Use the Intel Energy Profiler to run the Energy analysis with the Intel SoC Watch collector directly in the target Android system and view the collected data with the VTune Amplifier for Systems installed on the host Windows* or Linux* system.

    Analyzing Energy Usage on a Windows* Platform
    Duration: 20-30 minutes

    Tutorial
    Windows* OS: HTML | PDF
    Sample code: Pi_Console.exe

    Use the Intel Energy Profiler to run energy analysis of an idle system and a sample application with the Intel SoC Watch collector directly in the target Windows* system. Copy the results to the Windows host system and view the collected data with VTune Amplifier for Systems.

    Android* and Crosswalk Cordova Version Code Issues

    $
    0
    0

    The release of Apache* Cordova* CLI 5 by the Apache Cordova project resulted in a change to how the android:versionCode parameter is calculated for apps built with the Intel® XDK using CLI 5. The android:versionCode is found in the AndroidManifest.xml file of every Android* and Android-Crosswalk APK; it is directly derived from the App Version Code field in the Build Settings section of the Projects tab:

    If you have never published an app to an Android* store this change in behavior will have no impact on you. It might prevent side-loading an update to your app; in which case, simply uninstall the previously side-loaded app before installing your updated app.

    New (CLI 5) App Version Code Algorithm for Android

    Beginning with Cordova CLI 5, in order to maintain compatibility with standard Cordova, the Intel XDK no longer modifies the android:versionCode when building for Android-Crosswalk. Instead, the new Cordova CLI 5 encoding technique has been adopted for all Android builds. This change results in a discrepancy in the value of the android:versionCode that is inserted into your Android APK files when compared to building with CLI 4.1.2 (and earlier).

    Here's what Cordova CLI 5 (Cordova-Android 4.x) does with the android:versionCode (App Version Code) number when you perform a Crosswalk build:

    • multiplies your android:versionCode by 10
    • adds 2 to the android:versionCode for Crosswalk ARM builds
    • adds 4 to the android:versionCode for Crosswalk x86 builds

    Here's what Cordova CLI 5 (Cordova-Android 4.x) does with the android:versionCode (App Version Code) number when you perform a standard Android build (a non-Crosswalk build):

    • multiplies your android:versionCode by 10
    • adds 0 to the android:versionCode if the Minimum Android API is < 14
    • adds 8 to the android:versionCode if the Minimum Android API is 14-19
    • adds 9 to the android:versionCode if the Minimum Android API is > 19 (i.e., >= 20)

    So this means the Android store will find the following android:versionCode values inside your built APK if you set the App Version Code field to one in the Build Settings section of the Projects tab:

    • an App Version Code = "1" in the Build Settings section of Intel XDK Projects tab results in:
    • android:versionCode = "10" for a regular Android build if the android:minSdkVersion is < 14
    • android:versionCode = "12" for an Android-Crosswalk embedded library ARM build
    • android:versionCode = "14" for an Android-Crosswalk embedded library x86 build
    • android:versionCode = "18" for a regular Android build if the android:minSdkVersion is 14-19
    • android:versionCode = "19" for a regular Android build if the android:minSdkVersion is > 19

    NOTE: the Minimum Android* API field in the Build Settings section of the Projects tab corresponds to the value of the android:minSdkVersion number referenced in the bullets above.

    This scheme results in an x86 APK file that contains a version code that is greater than the ARM APK file. This condition is necessary to insure that the Android store delivers the appropriate architecture APK file to the requesting device. In this scheme, the x86 APK version code is always two greater than the ARM APK version code.

    NOTE: the Intel XDK build system generates two APK files (one marked x86 and one marked ARM) when you elect the shared Crosswalk build option, even though only one APK is required. The only difference between these two shared model APK files is the version code, which follows the same android:versionCode scheme as the embedded Crosswalk build option.

    If you HAVE PREVIOUSLY PUBLISHED an Android-Crosswalk app to an Android store, built with the Intel XDK CLI 4.1.2 option (or earlier), the new android:versionCode scheme described above may impact your ability to publish an update of your app! If you encounter that case, add 6000 (six with three zeroes) to your existing App Version Code field in the Build Settings section of the Projects tab. Your Crosswalk apps that were built with CLI 4.1.2 used a system that adds 60000 and 20000 (six with four zeros and two with four zeroes) to the android:versionCode. That scheme is described in more detail, below.

    If you have only published standard Android apps (non-Crosswalk) in the past, and are still publishing standard Android apps, you should not have to make any changes to the App Version Code field in the Android Builds Settings section of the Projects tab (other than increasing it by one for a new version).

    NOTE:

    • Android API 14 corresponds to Android 4.0
    • Android API 19 corresponds to Android 4.4
    • Android API 20 corresponds to Android 5.0
    • CLI 5 and above (Cordova-Android 4.x) does not support Android 2.x or Android 3.x

    Historic (CLI 4) App Version Code Algorithm for Android

    In the past (CLI 4.1.2 and earlier), standard Cordova did not modify the Android version code, so the android:versionCode found in your Android APK by the store was identical to the value provided in the App Version Code field. In order to support the submission of multiple Android-Crosswalk APK files (e.g., ARM and x86) to an Android store, the Intel XDK build system did modify the version code for Android-Crosswalk embedded builds (and only for Android-Crosswalk embedded builds, Crosswalk shared and regular Android build version codes were not modified by the build system).

    The "historic" behavior of the Intel XDK build system regarding the Android version code that was inserted into your APK files, when built using CLI 4.1.2 (or earlier) was:

    • no change to the version code for regular Android builds (android:versionCode = App Version Code)
    • no change to the version code for Android-Crosswalk shared library builds
    • add 60000 to the version code for Android-Crosswalk x86 embedded library builds
    • add 20000 to the version code for Android-Crosswalk ARM embedded library builds

    So this meant that you would find the following android:versionCode values inside your APK files, if you had set the App Version Code field to a value of one in the Build Settings section of the Projects tab and set the CLI version to 4.1.2:

    • an App Version Code = "1" in the Build Settings section of Intel XDK Projects tab results in:
    • android:versionCode = "1" for a regular Android build
    • android:versionCode = "1" for an Android-Crosswalk shared library build
    • android:versionCode = "20001" for an Android-Crosswalk embedded library ARM build
    • android:versionCode = "60001" for an Android-Crosswalk embedded library x86 build

    This scheme was used to insure that the x86 APK contained a higher version code than the equivalent ARM APK, and also so that both APKs contained larger version codes than a generic Android APK that you might use, for example, to provide an app to Android 2.x and 3.x devices (because Android-Crosswalk requires at least Android 4.0). Putting a larger version code into the x86 APK makes sure that the Android store will deliver the x86 APK to x86 devices, rather than incorrectly delivering an ARM APK to x86 devices.

    Intel® XDK FAQs - Cordova

    $
    0
    0

    How do I set app orientation?

    You set the orientation under the Build Settings section of the Projects tab.

    To control the orientation of an iPad you may need to create a simply plugin that contains a single plugin.xml file like the following:

    <config-file target="*-Info.plist" parent="UISupportedInterfaceOrientations~ipad" overwrite="true"><string></string></config-file><config-file target="*-Info.plist" parent="UISupportedInterfaceOrientations~ipad" overwrite="true"><array><string>UIInterfaceOrientationPortrait</string></array></config-file> 

    Then add the plugin as a local plugin using the plugin manager on the Projects tab.

    HINT: to import the plugin.xml file you created above, you must select the folder that contains the plugin.xml file; you cannot select the plugin.xml file itself, using the import dialg, because a typical plugin consists of many files, not a single plugin.xml. The plugin you created based on the instructions above only requires a single file, it is an atypical plugin.

    Alternatively, you can use this plugin: https://github.com/yoik/cordova-yoik-screenorientation. Import it as a third-party Cordova* plugin using the plugin manager with the following information:

    • cordova-plugin-screen-orientation
    • specify a version (e.g. 1.4.0) or leave blank for the "latest" version

    Or, you can reference it directly from its GitHub repo:

    To use the screen orientation plugin referenced above you must add some JavaScript code to your app to manipulate the additional JavaScript API that is provided by this plugin. Simply adding the plugin will not automatically fix your orientation, you must add some code to your app that takes care of this. See the plugin's GitHub repo for details on how to use that API.

    Is it possible to create a background service using Intel XDK?

    Background services require the use of specialized Cordova* plugins that need to be created specifically for your needs. Intel XDK does not support development or debug of plugins, only the use of them as "black boxes" with your HTML5 app. Background services can be accomplished using Java on Android or Objective C on iOS. If a plugin that backgrounds the functions required already exists (for example, this plugin for background geo tracking), Intel XDK's build system will work with it.

    How do I send an email from my App?

    You can use the Cordova* email plugin or use web intent - PhoneGap* and Cordova* 3.X.

    How do you create an offline application?

    You can use the technique described here by creating an offline.appcache file and then setting it up to store the files that are needed to run the program offline. Note that offline applications need to be built using the Cordova* or Legacy Hybrid build options.

    How do I work with alarms and timed notifications?

    Unfortunately, alarms and notifications are advanced subjects that require a background service. This cannot be implemented in HTML5 and can only be done in native code by using a plugin. Background services require the use of specialized Cordova* plugins that need to be created specifically for your needs. Intel XDK does not support the development or debug of plugins, only the use of them as "black boxes" with your HTML5 app. Background services can be accomplished using Java on Android or Objective C on iOS. If a plugin that backgrounds the functions required already exists (for example, this plugin for background geo tracking) the Intel XDK's build system will work with it.

    How do I get a reliable device ID?

    You can use the Phonegap/Cordova* Unique Device ID (UUID) plugin for Android*, iOS* and Windows* Phone 8.

    How do I implement In-App purchasing in my app?

    There is a Cordova* plugin for this. A tutorial on its implementation can be found here. There is also a sample in Intel XDK called 'In App Purchase' which can be downloaded here.

    How do I install custom fonts on devices?

    Fonts can be considered as an asset that is included with your app, not shared among other apps on the device just like images and CSS files that are private to the app and not shared. It is possible to share some files between apps using, for example, the SD card space on an Android* device. If you include the font files as assets in your application then there is no download time to consider. They are part of your app and already exist on the device after installation.

    How do I access the device's file storage?

    You can use HTML5 local storage and this is a good article to get started with. Alternatively, there is aCordova* file plugin for that.

    Why isn't AppMobi* push notification services working?

    This seems to be an issue on AppMobi's end and can only be addressed by them. PushMobi is only available in the "legacy" container. AppMobi* has not developed a Cordova* plugin, so it cannot be used in the Cordova* build containers. Thus, it is not available with the default build system. We recommend that you consider using the Cordova* push notification plugin instead.

    How do I configure an app to run as a service when it is closed?

    If you want a service to run in the background you'll have to write a service, either by creating a custom plugin or writing a separate service using standard Android* development tools. The Cordova* system does not facilitate writing services.

    How do I dynamically play videos in my app?

    1. Download the Javascript and CSS files from https://github.com/videojs and include them in your project file.
    2. Add references to them into your index.html file.
    3. Add a panel 'main1' that will be playing the video. This panel will be launched when the user clicks on the video in the main panel.

       
      <div class="panel" id="main1" data-appbuilder-object="panel" style=""><video id="example_video_1" class="video-js vjs-default-skin" controls="controls" preload="auto" width="200" poster="camera.png" data-setup="{}"><source src="JAIL.mp4" type="video/mp4"><p class="vjs-no-js">To view this video please enable JavaScript*, and consider upgrading to a web browser that <a href=http://videojs.com/html5-video-support/ target="_blank">supports HTML5 video</a></p></video><a onclick="runVid3()" href="#" class="button" data-appbuilder-object="button">Back</a></div>
    4. When the user clicks on the video, the click event sets the 'src' attribute of the video element to what the user wants to watch.

       
      Function runVid2(){
            Document.getElementsByTagName("video")[0].setAttribute("src","appdes.mp4");
            $.ui.loadContent("#main1",true,false,"pop");
      }
    5. The 'main1' panel opens waiting for the user to click the play button.

    NOTE: The video does not play in the emulator and so you will have to test using a real device. The user also has to stop the video using the video controls. Clicking on the back button results in the video playing in the background.

    How do I design my Cordova* built Android* app for tablets?

    This page lists a set of guidelines to follow to make your app of tablet quality. If your app fulfills the criteria for tablet app quality, it can be featured in Google* Play's "Designed for tablets" section.

    How do I resolve icon related issues with Cordova* CLI build system?

    Ensure icon sizes are properly specified in the intelxdk.config.additions.xml. For example, if you are targeting iOS 6, you need to manually specify the icons sizes that iOS* 6 uses.

    <icon platform="ios" src="images/ios/72x72.icon.png" width="72" height="72" /><icon platform="ios" src="images/ios/57x57.icon.png" width="57" height="57" />

    These are not required in the build system and so you will have to include them in the additions file.

    For more information on adding build options using intelxdk.config.additions.xml, visit: /en-us/html5/articles/adding-special-build-options-to-your-xdk-cordova-app-with-the-intelxdk-config-additions-xml-file

    Is there a plugin I can use in my App to share content on social media?

    Yes, you can use the PhoneGap Social Sharing plugin for Android*, iOS* and Windows* Phone.

    Iframe does not load in my app. Is there an alternative?

    Yes, you can use the inAppBrowser plugin instead.

    Why are intel.xdk.istablet and intel.xdk.isphone not working?

    Those properties are quite old and is based on the legacy AppMobi* system. An alternative is to detect the viewport size instead. You can get the user's screen size using screen.width and screen.height properties (refer to this article for more information) and control the actual view of the webview by using the viewport meta tag (this page has several examples). You can also look through this forum thread for a detailed discussion on the same.

    How do I enable security in my app?

    We recommend using the App Security API. App Security API is a collection of JavaScript API for Hybrid HTML5 application developers. It enables developers, even those who are not security experts, to take advantage of the security properties and capabilities supported by the platform. The API collection is available to developers in the form of a Cordova plugin (JavaScript API and middleware), supported on the following operating systems: Windows, Android & iOS.
    For more details please visit: https://software.intel.com/en-us/app-security-api.

    For enabling it, please select the App Security plugin on the plugins list of the Project tab and build your app as a Cordova Hybrid app. After adding the plugin, you can start using it simply by calling its API. For more details about how to get started with the App Security API plugin, please see the relevant sample app articles at: https://software.intel.com/en-us/xdk/article/my-private-photos-sample and https://software.intel.com/en-us/xdk/article/my-private-notes-sample.

    Why does my build fail with Admob plugins? Is there an alternative?

    Intel XDK does not support the library project that has been newly introduced in the com.google.playservices@21.0.0 plugin. Admob plugins are dependent on "com.google.playservices", which adds Google* play services jar to project. The "com.google.playservices@19.0.0" is a simple jar file that works quite well but the "com.google.playservices@21.0.0" is using a new feature to include a whole library project. It works if built locally with Cordova CLI, but fails when using Intel XDK.

    To keep compatible with Intel XDK, the dependency of admob plugin should be changed to "com.google.playservices@19.0.0".

    Why does the intel.xdk.camera plugin fail? Is there an alternative?

    There seem to be some general issues with the camera plugin on iOS*. An alternative is to use the Cordova camera plugin, instead and change the version to 0.3.3.

    How do I resolve Geolocation issues with Cordova?

    Give this app a try, it contains lots of useful comments and console log messages. However, use Cordova 0.3.10 version of the geo plugin instead of the Intel XDK geo plugin. Intel XDK buttons on the sample app will not work in a built app because the Intel XDK geo plugin is not included. However, they will partially work in the Emulator and Debug. If you test it on a real device, without the Intel XDK geo plugin selected, you should be able to see what is working and what is not on your device. There is a problem with the Intel XDK geo plugin. It cannot be used in the same build with the Cordova geo plugin. Do not use the Intel XDK geo plugin as it will be discontinued.

    Geo fine might not work because of the following reasons:

    1. Your device does not have a GPS chip
    2. It is taking a long time to get a GPS lock (if you are indoors)
    3. The GPS on your device has been disabled in the settings

    Geo coarse is the safest bet to quickly get an initial reading. It will get a reading based on a variety of inputs, but is usually not as accurate as geo fine but generally accurate enough to know what town you are located in and your approximate location in that town. Geo coarse will also prime the geo cache so there is something to read when you try to get a geo fine reading. Ensure your code can handle situations where you might not be getting any geo data as there is no guarantee you'll be able to get a geo fine reading at all or in a reasonable period of time. Success with geo fine is highly dependent on a lot of parameters that are typically outside of your control.

    Is there an equivalent Cordova* plugin for intel.xdk.player.playPodcast? If so, how can I use it?

    Yes, there is and you can find the one that best fits the bill from the Cordova* plugin registry.

    To make this work you will need to do the following:

    • Detect your platform (you can use uaparser.js or you can do it yourself by inspecting the user agent string)
    • Include the plugin only on the Android* platform and use <video> on iOS*.
    • Create conditional code to do what is appropriate for the platform detected

    You can force a plugin to be part of an Android* build by adding it manually into the additions file. To see what the basic directives are to include a plugin manually:

    1. Include it using the "import plugin" dialog, perform a build and inspect the resulting intelxdk.config.android.xml file.
    2. Then remove it from your Project tab settings, copy the directive from that config file and paste it into the intelxdk.config.additions.xml file. Prefix that directive with <!-- +Android* -->.

    More information is available here and this is what an additions file can look like:

    <preference name="debuggable" value="true" /><preference name="StatusBarOverlaysWebView" value="false" /><preference name="StatusBarBackgroundColor" value="#000000" /><preference name="StatusBarStyle" value="lightcontent" /><!-- -iOS* --><intelxdk:plugin intelxdk:value="nl.nielsad.cordova.wifiscanner" /><!-- -Windows*8 --><intelxdk:plugin intelxdk:value="nl.nielsad.cordova.wifiscanner" /><!-- -Windows*8 --><intelxdk:plugin intelxdk:value="org.apache.cordova.statusbar" /><!-- -Windows*8 --><intelxdk:plugin intelxdk:value="https://github.com/EddyVerbruggen/Flashlight-PhoneGap-Plugin" />

    This sample forces a plugin included with the "import plugin" dialog to be excluded from the platforms shown. You can include it only in the Android* platform by using conditional code and one or more appropriate plugins.

    How do I display a webpage in my app without leaving my app?

    The most effective way to do so is by using inAppBrowser.

    Does Cordova* media have callbacks in the emulator?

    While Cordova* media objects have proper callbacks when using the debug tab on a device, the emulator doesn't report state changes back to the Media object. This functionality has not been implemented yet. Under emulation, the Media object is implemented by creating an <audio> tag in the program under test. The <audio> tag emits a bunch of events, and these could be captured and turned into status callbacks on the Media object.

    Why does the Cordova version number not match the Projects tab's Build Settings CLI version number, the Emulate tab, App Preview and my built app?

    This is due to the difficulty in keeping different components in sync and is compounded by the version numbering convention that the Cordova project uses to distinguish build tool versions (the CLI version) from platform framework versions (the Cordova framework version) and plugin versions.

    The CLI version you specify in the Projects tab's Build Settings section is the "Cordova CLI" version that the build system uses to build your app. Each version of the Cordova CLI tools come with a set of "pinned" Cordova platform framework versions, which are tied to the target platform.

    NOTE: the specific Cordova platform framework versions shown below are subject to change without notice.

    Our Cordova CLI 4.1.2 build system is "pinned" to: 

    • cordova-android@3.6.4 (Android Cordova framework version 3.6.4)
    • cordova-ios@3.7.0 (iOS Cordova framework version 3.7.0)
    • cordova-windows@3.7.0 (Cordova Windows framework version 3.7.0)

    Our Cordova CLI 5.1.1 build system is "pinned" to:

    • cordova-android@4.1.1 (as of March 23, 2016)
    • cordova-ios@3.8.0
    • cordova-windows@4.0.0

    Our Cordova CLI 5.4.1 build system is "pinned" to: 

    • cordova-android@5.0.0
    • cordova-ios@4.0.1
    • cordova-windows@4.3.1

    Our CLI 5.4.1 build system really should be called "CLI 5.4.1+" because the platform framework versions it uses are closer to the "pinned" versions in the Cordova CLI 6.0.0 release than those "pinned" in the original CLI 5.4.1 release.

    The Cordova platform framework version you get when you build an app does not equal the CLI version number in the Build Settings section of the Projects tab; it equals the Cordova platform framework version that is "pinned" to our build system's CLI version (see the list of pinned versions, above).

    Technically, the target-specific Cordova frameworks can be updated [independently] for a given version of CLI tools. In some cases, our build system may use a Cordova platform framework version that is later than the version that was "pinned" to the CLI when it was originally released by the Cordova project (that is, the Cordova framework versions originally specified by the Cordova CLI x.y.z links above).

    The reasons you may see Cordova framework version differences between the Emulate tab, App Preview and your built app are:

    • The Emulate tab has one specific Cordova framework version built into it. We try to make sure that version of the Cordova framework closely matches the default Intel XDK version of Cordova CLI.
    • App Preview is released independently of the Intel XDK and, therefore, may use a different version than what you will see reported by the Emulate tab or your built app. Again, we try to release App Preview so it matches the version of the Cordova framework that is considered the default version for the Intel XDK at the time App Preview is released; but since the various tools are not always released in perfect sync, that is not always possible.
    • Your app is built with a "pinned" Cordova platform framework version, which is determined by the Cordova CLI version you specified in the Projects tab's Build Settings section. There are always at least two different CLI versions available in the Intel XDK build system.
    • For those versions of Crosswalk that are built with the Intel XDK CLI 4.1.2 build system, the cordova-android framework version is determined by the Crosswalk project, not by the Intel XDK build system.
    • For those versions of Crosswalk that are built with Intel XDK CLI 5.1.1 and later build systems, the cordova-android framework version equals that specified in the lists above (it equals the "pinned" cordova-android platform version for that CLI version).

    Do these Cordova framework version numbers matter? Occasionally, yes, but normally, not that much. There are some issues that come up that are related to the Cordova framework version, but they tend to be rare. The majority of the bugs and compatibility issues you will experience in your app have more to do with the versions and mix of Cordova plugins you choose to use and the HTML5 webview runtime on your test devices. See this blog for more details about what a webview is and why the webview matters to your app: When is an HTML5 Web App a WebView App?.

    The "default version" of the CLI that the Intel XDK uses is rarely the most recent version of the Cordova CLI tools distributed by the Cordova project. There is always a lag between Cordova project releases and our ability to incorporate those releases into our build system and the various Intel XDK components. We are not able to provide every release that is made by the Cordova project.

    How do I add a third party plugin?

    Please follow the instructions on this doc page to add a third-party plugin: Adding Plugins to Your Intel® XDK Cordova* App -- this plugin is not being included as part of your app. You will see it in the build log if it was successfully added to your build.

    How do I make an AJAX call that works in my browser work in my app?

    Please follow the instructions in this article: Cordova CLI 4.1.2 Domain Whitelisting with Intel XDK for AJAX and Launching External Apps.

    I get an "intel is not defined" error, but my app works in Test tab, App Preview and Debug tab. What's wrong?

    When your app runs in the Test tab, App Preview or the Debug tab the intel.xdk and core Cordova functions are automatically included for easy debug. That is, the plugins required to implement those APIs on a real device are already included in the corresponding debug modules.

    When you build your app you must include the plugins that correspond to the APIs you are using in your build settings. This means you must enable the Cordova and/or XDK plugins that correspond to the APIs you are using. Go to the Projects tab and insure that the plugins you need are selected in your project's plugin settings. See Adding Plugins to Your Intel® XDK Cordova* App for additional details.

    How do I target my app for use only on an iPad or only on an iPhone?

    There is an undocumented feature in Cordova that should help you (the Cordova project provided this feature but failed to document it for the rest of the world). If you use the appropriate preference in theintelxdk.config.additions.xml file you should get what you need:

    <preference name="target-device" value="tablet" />     <!-- Installs on iPad, not on iPhone --><preference name="target-device" value="handset" />    <!-- Installs on iPhone, iPad installs in a zoomed view and doesn't fill the entire screen --><preference name="target-device" value="universal" />  <!-- Installs on iPhone and iPad correctly -->

    If you need info regarding the additions.xml file, see the blank template or this doc file: Adding Intel® XDK Cordova Build Options Using the Additions File.

    Why does my build fail when I try to use the Cordova* Capture Plugin?

    The Cordova* Capture plugin has a dependency on the File Plugin. Please make sure you both plugins selected on the projects tab.

    How can I pinch and zoom in my Cordova* app?

    For now, using the viewport meta tag is the only option to enable pinch and zoom. However, its behavior is unpredictable in different webviews. Testing a few samples apps has led us to believe that this feature is better on Crosswalk for Android. You can test this by building the Hello Cordova sample app for Android and Crosswalk for Android. Pinch and zoom will work on the latter only though they both have:

    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes, minimum-scale=1, maximum-scale=2">.

    Please visit the following pages to get a better understanding of when to build with Crosswalk for Android:

    http://blogs.intel.com/evangelists/2014/09/02/html5-web-app-webview-app/

    https://software.intel.com/en-us/xdk/docs/why-use-crosswalk-for-android-builds

    Another device oriented approach is to enable it by turning on Android accessibility gestures.

    How do I make my Android application use the fullscreen so that the status and navigation bars disappear?

    The Cordova* fullscreen plugin can be used to do this. For example, in your initialization code, include this function AndroidFullScreen.immersiveMode(null, null);.

    You can get this third-party plugin from here https://github.com/mesmotronic/cordova-fullscreen-plugin

    How do I add XXHDPI and XXXHDPI icons to my Android or Crosswalk application?

    The Cordova CLI 4.1.2 build system will support this feature, but our 4.1.2 build system (and the 2170 version of the Intel XDK) does not handle the XX and XXX sizes directly. Use this workaround until these sizes are supported directly:

    • copy your XX and XXX icons into your source directory (usually named www)
    • add the following lines to your intelxdk.config.additions.xml file
    • see this Cordova doc page for some more details

    Assuming your icons and splash screen images are stored in the "pkg" directory inside your source directory (your source directory is usually named www), add lines similar to these into yourintelxdk.config.additions.xml file (the precise name of your png files may be different than what is shown here):

    <!-- for adding xxhdpi and xxxhdpi icons on Android --><icon platform="android" src="pkg/xxhdpi.png" density="xxhdpi" /><icon platform="android" src="pkg/xxxhdpi.png" density="xxxhdpi" /><splash platform="android" src="pkg/splash-port-xhdpi.png" density="port-xhdpi"/><splash platform="android" src="pkg/splash-land-xhdpi.png" density="land-xhdpi"/>

    The precise names of your PNG files are not important, but the "density" designations are very important and, of course, the respective resolutions of your PNG files must be consistent with Android requirements. Those density parameters specify the respective "res-drawable-*dpi" directories that will be created in your APK for use by the Android system. NOTE: splash screen references have been added for reference, you do not need to use this technique for splash screens.

    You can continue to insert the other icons into your app using the Intel XDK Projects tab.

    Which plugin is the best to use with my app?

    We are not able to track all the plugins out there, so we generally cannot give you a "this is better than that" evaluation of plugins. Check the Cordova plugin registry to see which plugins are most popular and check Stack Overflow to see which are best supported; also, check the individual plugin repos to see how well the plugin is supported and how frequently it is updated. Since the Cordova platform and the mobile platforms continue to evolve, those that are well-supported are likely to be those that have good activity in their repo.

    Keep in mind that the XDK builds Cordova apps, so whichever plugins you find being supported and working best with other Cordova (or PhoneGap) apps would likely be your "best" choice.

    See Adding Plugins to Your Intel® XDK Cordova* App for instructions on how to include third-party plugins with your app.

    What are the rules for my App ID?

    The precise App ID naming rules vary as a function of the target platform (eg., Android, iOS, Windows, etc.). Unfortunately, the App ID naming rules are further restricted by the Apache Cordova project and sometimes change with updates to the Cordova project. The Cordova project is the underlying technology that your Intel XDK app is based upon; when you build an Intel XDK app you are building an Apache Cordova app.

    CLI 5.1.1 has more restrictive App ID requirements than previous versions of Apache Cordova (the CLI version refers to Apache Cordova CLI release versions). In this case, the Apache Cordova project decided to set limits on acceptable App IDs to equal the minimum set for all platforms. We hope to eliminate this restriction in a future release of the build system, but for now (as of the 2496 release of the Intel XDK), the current requirements for CLI 5.1.1 are:

    • Each section of the App ID must start with a letter
    • Each section can only consist of letters, numbers, and the underscore character
    • Each section cannot be a Java keyword
    • The App ID must consist of at least 2 sections (each section separated by a period ".").

    iOS /usr/bin/codesign error: certificate issue for iOS app?

    If you are getting an iOS build fail message in your detailed build log that includes a reference to a signing identity error you probably have a bad or inconsistent provisioning file. The "no identity found" message in the build log excerpt, below, means that the provisioning profile does not match the distribution certificate that was uploaded with your application during the build phase.

    Signing Identity:     "iPhone Distribution: XXXXXXXXXX LTD (Z2xxxxxx45)"
    Provisioning Profile: "MyProvisioningFile"
                          (b5xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxe1)
    
        /usr/bin/codesign --force --sign 9AxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxA6 --resource-rules=.../MyApp/platforms/ios/build/device/MyApp.app/ResourceRules.plist --entitlements .../MyApp/platforms/ios/build/MyApp.build/Release-iphoneos/MyApp.build/MyApp.app.xcent .../MyApp/platforms/ios/build/device/MyApp.app
    9AxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxA6: no identity found
    Command /usr/bin/codesign failed with exit code 1
    
    ** BUILD FAILED **
    
    
    The following build commands failed:
        CodeSign build/device/MyApp.app
    (1 failure)
    

    The excerpt shown above will appear near the very end of the detailed build log. The unique number patterns in this example have been replaced with "xxxx" strings for security reasons. Your actual build log will contain hexadecimal strings.

    iOS Code Sign error: bundle ID does not match app ID?

    If you are getting an iOS build fail message in your detailed build log that includes a reference to a "Code Sign error" you may have a bad or inconsistent provisioning file. The "Code Sign" message in the build log excerpt, below, means that the bundle ID you specified in your Apple provisioning profile does not match the app ID you provided to the Intel XDK to upload with your application during the build phase.

    Code Sign error: Provisioning profile does not match bundle identifier: The provisioning profile specified in your build settings (MyBuildSettings) has an AppID of my.app.id which does not match your bundle identifier my.bundleidentifier.
    CodeSign error: code signing is required for product type 'Application' in SDK 'iOS 8.0'
    
    ** BUILD FAILED **
    
    The following build commands failed:
        Check dependencies
    (1 failure)
    Error code 65 for command: xcodebuild with args: -xcconfig,...
    

    The message above translates into "the bundle ID you entered in the project settings of the XDK does not match the bundle ID (app ID) that you created on Apples developer portal and then used to create a provisioning profile."

    What are plugin variables used for? Why do I need to supply plugin variables?

    Some plugins require details that are specific to your app or your developer account. For example, to authorize your app as an app that belongs to you, the developer, so services can be properly routed to the service provider. The precise reasons are dependent on the specific plugin and its function.

    What happened to the Intel XDK "legacy" build options?

    On December 14, 2015 the Intel XDK legacy build options were retired and are no longer available to build apps. The legacy build option is based on three year old technology that predates the current Cordova project. All Intel XDK development efforts for the past two years have been directed at building standard Apache Cordova apps.

    Many of the intel.xdk legacy APIs that were supported by the legacy build options have been migrated to standard Apache Cordova plugins and published as open source plugins. The API details for these plugins are available in the README.md files in the respective 01.org GitHub repos. Additional details regarding the new Cordova implementations of the intel.xdk legacy APIs are available in the doc page titled Intel XDK Legacy APIs.

    Standard Cordova builds do not require the use of the "intelxdk.js" and "xhr.js" phantom scripts. Only the "cordova.js" phantom script is required to successfully build Cordova apps. If you have been including "intelxdk.js" and "xhr.js" in your Cordova builds they have been quietly ignored. You should remove references to these files from your "index.html" file; leaving them in will do no harm, it simply results in a warning that the respective script file cannot be found at runtime.

    The Emulate tab will continue to support some legacy intel.xdk APIs that are NOT supported in the Cordova builds (only those intel.xdk APIs that are supported by the open source plugins are available to a Cordova built app, and only if you have included the respective intel.xdk plugins). This Emulate tab discrepancy will be addressed in a future release of the Intel XDK.

    More information can be found in this forum post > https://software.intel.com/en-us/forums/intel-xdk/topic/601436.

    Which build files do I submit to the Windows Store and which do I use for testing my app on a device?

    There are two things you can do with the build files generated by the Intel XDK Windows build options: side-load your app onto a real device (for testing) or publish your app in the Windows Store (for distribution). Microsoft has changed the files you use for these purposes with each release of a new platform. As of December, 2015, the packages you might see in a build, and their uses, are:

    • appx works best for side-loading, and can also be used to publish your app.
    • appxupload is preferred for publishing your app, it will not work for side-loading.
    • appxbundle will work for both publishing and side-loading, but is not preferred.
    • xap is for legacy Windows Phone; works for both publishing and side-loading.

    In essence: XAP (WP7) was superseded by APPXBUNDLE (Win8 and WP8.0), which was superseded by APPX (Win8/WP8.1/UAP), which has been supplemented with APPXUPLOAD. APPX and APPXUPLOAD are the preferred formats. For more information regarding these file formats, see Upload app packages on the Microsoft developer site.

    Side-loading a Windows Phone app onto a real device, over USB, requires a Windows 8+ development system (see Side-Loading Windows* Phone Apps for complete instructions). If you do not have a physical Windows development machine you can use a virtual Windows machine or use the Window Store Beta testing and targeted distribution technique to get your app onto real test devices.

    Side-loading a Windows tablet app onto a Windows 8 or Windows 10 laptop or tablet is simpler. Extract the contents of the ZIP file that you downloaded from the Intel XDK build system, open the "*_Test" folder inside the extracted folder, and run the PowerShell script (ps1 file) contained within that folder on the test machine (the machine that will run your app). The ps1 script file may need to request a "developer certificate" from Microsoft before it will install your test app onto your Windows test system, so your test machine may require a network connection to successfully side-load your Windows app.

    The side-loading process may not over-write an existing side-loaded app with the same ID. To be sure your test app properly side-loads, it is best to uninstall the old version of your app before side-loading a new version on your test system.

    How do I implement local storage or SQL in my app?

    See this summary of local storage options for Cordova apps written by Josh Morony, A Summary of Local Storage Options for PhoneGap Applications.

    How do I prevent my app from auto-completing passwords?

    Use the Ionic Keyboard plugin and set the spellcheck attribute to false.

    Why does my PHP script not run in my Intel XDK Cordova app?

    Your XDK app is not a page on a web server; you cannot use dynamic web server techniques because there is no web server associated with your app to which you can pass off PHP scripts and similar actions. When you build an Intel XDK app you are building a standalone Cordova client web app, not a dynamic server web app. You need to create a RESTful API on your server that you can then call from your client (the Intel XDK Cordova app) and pass and return data between the client and server through that RESTful API (usually in the form of a JSON payload).

    Please see this StackOverflow post and this article by Ray Camden, a longtime developer of the Cordova development environment and Cordova apps, for some useful background.

    Following is a lightly edited recommendation from an Intel XDK user:

    I came from php+mysql web development. My first attempt at an Intel XDK Cordova app was to create a set of php files to query the database and give me the JSON. It was a simple job, but totally insecure.

    Then I found dreamfactory.com, an open source software that automatically creates the REST API functions from several databases, SQL and NoSQL. I use it a lot. You can start with a free account to develop and test and then install it in your server. Another possibility is phprestsql.sourceforge.net, this is a library that does what I tried to develop by myself. I did not try it, but perhaps it will help you.

    And finally, I'm using PouchDB and CouchDB"A database for the web." It is not SQL, but is very useful and easy if you need to develop a mobile app with only a few tables. It will also work with a lot of tables, but for a simple database it is an easy place to start.

    I strongly recommend that you start to learn these new ways to interact with databases, you will need to invest some time but is the way to go. Do not try to use MySQL and PHP the old fashioned way, you can get it work but at some point you may get stuck.

    Why doesn’t my Cocos2D game work on iOS?

    This is an issue with Cocos2D and is not a reflection of our build system. As an interim solution, we have modified the CCBoot.js file for compatibility with iOS and App Preview. You can view an example of this modification in this CCBoot.js file from the Cocos2d-js 3.1 Scene GUI sample. The update has been applied to all cocos2D templates and samples that ship with Intel XDK. 

    The fix involves two lines changes (for generic cocos2D fix) and one additional line (for it to work on App Preview on iOS devices):

    Generic cocos2D fix -

    1. Inside the loadTxt function, xhr.onload should be defined as

    xhr.onload = function () {
        if(xhr.readyState == 4)
            xhr.responseText != "" ? cb(null, xhr.responseText) : cb(errInfo);
        };

    instead of

    xhr.onload = function () {
        if(xhr.readyState == 4)
            xhr.status == 200 ? cb(null, xhr.responseText) : cb(errInfo);
        };

    2. The condition inside _loadTxtSync function should be changed to 

    if (!xhr.readyState == 4 || (xhr.status != 200 || xhr.responseText != "")) {

    instead of 

    if (!xhr.readyState == 4 || xhr.status != 200) {

     

    App Preview fix -

    Add this line inside of loadTxtSync after _xhr.open:

    xhr.setRequestHeader("iap_isSyncXHR", "true");

     

    Back to FAQs Main

    Garbage Collection Workload for Android*

    $
    0
    0

    Download Document

    A New Way to Measure Android Garbage Collection Performance

    As the mobile computing market evolves, Google Android* has become one of the most popular software stacks for smart mobile devices. Because Java* is the primary implementation language for Android applications, the Java Virtual Machine (JVM) is key to providing the best Android user experience.

    The garbage collector (GC) component of JVM is one of its most important. It provides automatic memory management, and ensures that Java programmers cannot accidentally (or purposely) crash the JVM by incorrectly freeing memory, improving both programmer productivity and system security. GC keeps track of the objects currently referenced by the Java program, so it can reclaim the memory occupied by unreferenced objects, also known as “garbage.” Accurate and efficient garbage collection is critical to reaching high performance and to the user experience of Android applications.

    GC may interfere with user thread execution for garbage collection by introducing overhead and hence hurting performance and user experience. A typical example is that most GC algorithms require pausing all Java threads in an application at some point in order to guarantee that only garbage object memory is reclaimed. If the pause time is long, it can cause performance and user experience issues such as jank (unresponsive user interface or momentary sluggishness) and lack of responsiveness and smoothness. In addition, GC is usually triggered automatically by the JVM in the background, so programmers have little or no control over GC scheduling. Android developers must be aware of this hidden software component.

    To achieve the best performance and user experience by optimizing GC, a workload that reflects GC performance is indispensable. However, in our experience most popular Android workloads (gaming, parsing, security, etc.) stress GC only intermittently. Intel developed Garbage Collection Workload for Android (GCW for Android) to analyze GC performance and its influence on Android performance and user experience.

    GCW for Android stresses the memory management subsystem of the Android Runtime (ART). It is designed to be representative of the peak memory use behavior of Android applications, so optimizations based on GCW for Android analysis not only improve the workload score but also improve user experience. Further, GCW for Android provides options for you to adjust its behavior, making it flexible enough to mimic different kinds of application behavior.

    GCW for Android Overview

    Intel developed GCW for Android based on the analysis of real-world applications, including typical Android applications in categories such as business, communications, and entertainment. GCW for Android is an object allocation and GC intensive workload designed for GC performance evaluation and analysis.

    The workload has two working modes. You can run it from the command line or control it using a GUI. GCW for Android is configurable. You can specify the workload size, number of allocation threads, object allocation size distribution, and object lifetime distribution to fit different situations. It provides flexibility to test GC with different allocation behaviors, so you can use GCW for Android to analyze GC performance for most usage situations.

    GCW for Android incorporates several metrics. It reports the total execution time as the primary metric of GC and object allocation efficiency. The workload also reports memory usage information such as the Java heap footprint and total allocated object bytes based on the Android logging system.

    How to Run GCW for Android

    For the Android platform, GCW for Android is provided as a single package: GCW_Android.apk. After installing the apk, clicking the GCW_Android icon launches the workload and displays a UI that includes Start and Setting buttons.


    Figure 1. GCW for Android Launch UI

    Clicking the “Start” button will run the workload using the default profile settings. The “default” settings option is used to reset the workload profile to the default. If you want to change the configuration, click the “Settings” button.


    (a)


    (b)
    Figure 2. Configuration UI. (a) is the top part (b) is the bottom part

    The first setting is a selectable list of profiles. For now, “default” is the only option. A profile consists of the parameters used by the workload, and the default profile is derived from the characteristics of several real applications.

    Total Object size: Allows you to define the total object size allocated in one iteration by all allocation threads. The default is 100MB, which means that when running in multi-thread mode with four threads, each thread will allocate 25MB’s worth of objects in one iteration in the stress test phase.

    Bucket size: allows you to define the size of the binary trees that are built in a single allocation phase. The default is 1MB.

    Large object size: allows you to define the large object size. The default is 12KB, which is the minimum size object that ART allocates in the large object space.

    Object size distribution: allows you to define the size distribution of allocated objects. The total sum should be 100%.

    Large object element type distribution: allows you to define the lifetime for each object. An object’s lifetime is defined in units of the size of the objects (1MB by default) allocated from when it is created to when it is made unreachable. The first item in the lifetime data is the long lived object percentage (the percentage of objects that live for the entire workload run), the second is the percentage of objects that die after the first period, the third is the percentage of objects that die after the second period (after allocating another 1MB worth of objects), and the K’th item is the percentage of objects that die after the K+1’st period (after allocating K MB’s worth of objects). Items are separated by commas and each line should have the same number of items.

    By default, the workload runs in multi-thread mode. If you want to run in single-thread mode, check "Run in single thread?"

    To understand how GCW for Android reflects the JVM’s memory management characteristics and is representative of real applications, let’s go deeper to see how GCW for Android is designed.

    GCW for Android Design

    GCW for Android is designed to mimic the JVM memory management behavior that real applications exhibit. Detailed analysis of different user scenarios on a large number of popular Android applications indicate that Java programs create various sized objects with varying lifetimes, so the workload does too. Also, the default relationship between object sizes and lifetimes (small objects tend to have short lifetimes) and the multi-threaded allocation behavior are similar to those of real applications.

    Abstracted from the analysis data, the following characteristics were chosen as the primary design points for GCW for Android.

    Object size distribution

    Figure 3 shows a histogram of object size distribution based on 17 popular Google Play* store applications. The X-axis is the percent of all objects of a given object size range and the Y-axis is the object size range buckets.


    Figure 3. Object size distribution of popular apps

    When running, around 80% of the objects allocated are small objects whose size is less or equal to 64 bytes. We observed the same behavior on ~50 more popular apps, so GCW for Android uses objects with many different object sizes. How GCW for Android models object size will be discussed in the next section “GCW for Android Workflow.”

    Object lifetime

    Object lifetime is measured by how many garbage collections an object survives in the Java heap. Understanding object lifetime can help the JVM developer optimize GC performance by optimizing how GC works and tuning GC-related options.

    In our investigations, the lines plotting object size against object lifetime show a loose relationship between the two, but lifetime does seem to be related to the object size. Here we choose Gallery3D (Figure 4) and Google Maps* (Figure 5) as examples. The X-axis is the percentage of objects that die; the Y-axis is the number of GCs that survive. Each line represents an object size range.


    Figure 4. Gallery3D Object Lifetimes


    Figure 5. Google Maps*mapping serviceObject Lifetimes

    Most objects die after one to three GCs, but the lines aren’t quite congruent. For Google Maps, ~80% of the objects between 1-16 bytes die after the first GC, but only 60% of the objects between 33-64 bytes die after the first GC. Different-sized objects can have different lifetimes, so how well GCW for Android reflects object lifetime is an important design goal. How GCW for Android models object lifetime will be discussed in the next section “GCW for Android Workflow.”

    Multi-threading

    Our investigation shows that most Android Java applications are multi-threaded, though the threads do not typically communicate much with each other. Each Java application running on an Android device may have more than one thread allocating objects in the Java heap simultaneously. GCW for Android supports multi-threaded allocation in order to mimic this real application characteristic. How GCW for Android supports multi-threading will be explained in next section “GCW for Android Workflow.”

    To summarize, the following workload characteristics are emulated in GCW for Android. Typical Android applications:

    • Allocate varied size objects.
    • Have similar allocated object size distributions.
    • Have allocated objects with different lifetimes, and their lifetimes seem to be related to their size.
    • Allocate objects in parallel in multiple threads.

    Putting all these observations together, we designed the GCW for Android workflow to make it not only a JVM memory management workload, but also one that reflects actual usage scenarios.

    GCW for Android Workflow

    GCW for Android supports two threading modes: single- and multi-thread. While in multi-thread mode each thread is assigned a number, which is by default the logical CPU number. You can change it.


    (a)


    (b)
    Figure 6. GCW for Android Workflow

    Internally, GCW for Android builds several binary trees in order to manage object sizes and lifetimes. It builds and deletes objects by inserting and deleting nodes in the trees, as shown in Figure 6(b).

    Figures 6(a) and (b) show how GCW for Android works. It first launches a certain number of threads, and then each thread follows the same logic: allocate long lived objects and then stress test. The stress test is the most time consuming part of the workload and is a big loop that iterates a configurable number of times, by default 100. In each iteration, GCW for Android allocates a configurable number of bytes (by default 100MB), which by default includes 6 kinds of small objects (16, 24, 40, 96, 192, and 336 byte objects) plus large objects (12K bytes, configurable). Small objects are created as nodes of binary trees; large objects are created as byte, char, int, or long arrays. In each iteration of GCW for Android, the workload:

    • Builds binary trees.
    • Deletes some nodes from built trees according to the lifetimes of small objects.
    • Builds large object arrays.
    • Deletes some arrays according to lifetimes of large objects.

    Now let’s take a closer look at the internal design of GCW for Android to understand how it achieves the aforementioned characteristics of emulating memory system use.

    Object Size Distribution

    To simulate common object size distribution patterns, GCW for Android internally defines seven object size buckets:

    • 16 byte    →   [1-16B]
    • 24 byte    →   [17-32B]
    • 40 byte    →   [33-64B]
    • 96 byte    →   [65-128B]
    • 192 byte  →   [129-256B]
    • 336 byte  →   [257-512B]
    • Large object (default is 12KB)

    To conveniently abstract object references, GCW for Android allocates small sized objects as nodes in a binary tree, and large objects are created as arrays. There are four types of large object arrays: byte, char, int, and long.

    Now let’s see how GCW for Android manages object lifetimes to mimic real applications.

    Object Lifetime Control

    GCW for Android internally uses binary trees to control object lifetime. Every binary tree has a predefined lifetime. GCW for Android controls tree lifetimes and therefore object lifetimes.

    For example, suppose you want your object lifetime model to have three stages where 50% of objects die in period K, 25% of objects die after that in period K+1, and the remaining 25% live through period K+2.

    At the beginning of period K, GCW for Android builds three trees simultaneously, one tree for each lifetime stage. In period K, one tree holding 50% of the objects is made unreachable by assigning null to the root object, which makes the whole tree unreachable from the GC point of view. So 50% of the objects are collected by GC after period K. Then in period K+1, the second tree holding 25% of objects is rendered unreachable by setting the root to null, thus causing 25% of the objects to be reclaimed after period K+1 and leaving 25% of the objects alive through period K+2 (see Figure 7).


    Figure 7. Object lifetime control

    In different use scenarios, object lifetime is not deterministic, so GCW for Android also does not make object lifetimes deterministic. To emulate real applications, GCW for Android generates a random number for every thread, each with a different seed, in order to decide object size and the lifetime stage of a node. Here is an example.

    In this example three 24-byte objects will die after stage one, and the other objects will die after stage 0.

    To recap, GCW for Android makes it easy to reflect the object allocation and GC behavior of real applications. Using GCW for Android can help you identify many opportunities in the ART to enhance performance and user experience.

    Opportunities Discovered Using GCW for Android

    During our performance investigation we discovered that object allocation is typically the hottest part of an application. Further investigation showed that allocation can be made faster by inlining the RosAlloc allocation fast path, which means the call to the allocation function is eliminated. That resulted in ~7% improvement on GCW for Android. The implementation has been merged into the Android Open Source Project (AOSP).

    Additionally, we found that GC marking time can be reduced by eliminating unnecessary card table processing between immune spaces. The card table is a mechanism that records cross- space object references, which guarantee the correctness of GC when it collects only a subset of the Java heap (the subsets are called “spaces”) instead of the whole heap. Analysis also revealed that GC pause time can be reduced by clearing dirty cards for allocation spaces during partial and full GCs. Minimizing pause time is critical for end user apps because reducing pause time can reduce jank and improve smoothness.

    GCW for Android also helped us find GC optimization opportunities such as parallel marking and parallel sweeping. Intel has contributed several of these optimizations to AOSP and the rest have been added to the Intel ART binaries. Altogether, these optimizations have resulted in ~20% improvement on GCW for Android. All have helped improve Intel product performance and user experience.

    Open Source GCW for Android

    We have submitted GCW for Android for upstreaming into AOSP to make it available to the entire Android development community. Our goal has been to make GCW for Android the most realistic Android Java memory system workload and use it to drive GC optimization on all platforms to improve Android performance and user experience.

    Downloads

    The code can be downloaded from Google at

    https://android-review.googlesource.com/#/c/167279/

    Conclusion

    GCW for Android is a JVM memory management workload that is designed to emulate how real applications use Java memory management. It is intended to help both JVM and application developers optimize memory management and user experience on Android. Intel is using it to improve product performance and user experience by identifying optimization opportunities in ART. We hope it becomes an important indicator of performance and user experience on Android.

    References

    Java Virtual Machine (JVM): https://en.wikipedia.org/wiki/Java_virtual_machine
    Garbage Collection (GC): https://en.wikipedia.org/wiki/Garbage_collection_(computer_science)
    Android Runtime (ART): https://source.android.com/devices/tech/dalvik/
    Inside the Java Virtual Machine: https://www.artima.com/insidejvm/ed2/index.html

    Acknowledgements (alphabetical)

    Jean Christophe Beyler, Dong Yuan Chen, Haitao Feng, Jean-Philippe Halimi, Paul Hohensee, Aleksey Ignatenko, Rahul Kandu, Lei Li, Desikan Saravanan, Kumar Shiv, and Sushma Kyasaralli Thimmappa.

    About the Authors

    Li Wang is a software engineer in the Intel Software and Solutions Group (SSG), Systems Technologies & Optimizations (STO), Client Software Optimization (CSO). She focuses on Android workload development and memory management optimization in the Android Java runtime.

    Lin Zang is a software engineer in the Intel Software and Solutions Group (SSG), Systems Technologies & Optimizations (STO), Client Software Optimization (CSO). He focuses on memory management optimization and functional stability in the Android Java runtime.

    Google VP9 Optimization

    $
    0
    0

     

     

     

     

    Introduction

    We’ve all watched a movie or music video and become frustrated as it stalled or buffered right at the best part. Portals including YouTube*, Netflix*, and Amazon* work constantly to give customers the highest quality with the fastest streaming available. Toward that end, Intel gathered a team of senior engineers with very strong performance optimization backgrounds early in 2015 to tune the VP9 video codec for greater performance on the Intel® Atom™ platform.

    What is VP9?

    • It is a royalty-freeopen video format that Google is developing. Compare it to High Efficiency Video Coding (HEVC), which requires a license.
    • It is used for 4K-resolution content on YouTube*, other video services, and some smart TVs.
    • It supports HTML5 playback in Chrome*, Chromium*, Firefox*, and Opera*.

    How does it work?

    VP9 uses different-sized pixel blocks for encoding and decoding video content. Using a sophisticated algorithm, it systematically compresses raw data compactly to broadcast over an Internet stream. Specifically, VP9 can operate on a combination of block sizes from 64x64 down to 4x4 for various levels of detail, which makes it efficient for recreating everything from an open blue sky to the details of your loved one’s face.

    Further, VP9 includes 10 different prediction models to efficiently rebuild pictures during decoding and has a range of features to enhance reliability for streaming video content. This is critical for high-definition video. A full HD image has about 2 million pixels and potentially millions of colors making up an individual frame, with hundreds of thousands of frames making up a movie. Google has already announced plans to use VP9 for 4K content on YouTube*. The Google Play* store will also likely use VP9 for its streaming video service.

    Planning the Approach

    One of the first objectives for our team was to define our test case. VP9 is relevant across various types of streaming video, but we noted that generally a videoconference changes less, frame-to-frame, than a YouTube video. We decided to start with the simpler videoconference case. Our plan was to verify key optimizations in videoconferencing and then test them against more complex video usages.

    Our first architecture target was Bay Trail under 32-bit Android*. Once we achieved the best decode performance we could on Bay Trail, we would then focus on other platforms.

    Meeting the Challenge

    Our team, which included a principal engineer and an architect, used a CPU simulator to identify hotspots in the existing code. We used an iterative approach in optimization – possible issue identification using internal tools and micro-architectural knowledge, coding and measuring performance for new solution, and getting back to code review. Specifically, during WebM/libvpx optimization we came across of a lot of front-end related issues that we describe further below. These issues are easy to spot and fix and might provide substantial performance improvements to your application.

    Front-End starvation due to MSROM instruction flow

    One of the performance issues we found on Silvermont microarchitecture was excessive usage of pshufb instructions. According to the optimization manual [1], pshufb requires decoder assistance from MSROM and has 5-cycle throughput and latency.

    MSROM lookup creates a delay in the front-end and limits the number of instructions decoded per cycle. In many cases MSROM lookup penalty might be fine (when the back-end is not able to consume and execute uops at the higher rate), but if the number of such instructions is high, performance might suffer when there are no uops in the IDQ.

    We found that excessive pshufb instructions in the “vp9_filter_block1d16_h8_ssse3” function [2] were creating the issue explained above. In general, pshufb instructions rearrange bytes in the vector register based on an arbitrary mask.

    We drilled down to the actual operation that was required (see diagram below) using two pshufb instructions.

    We realized that exactly the same operation can be done using just four simple operations (punpcklbw, punpckhbw, and two palignr instructions) as shown on the next diagram.

    Optimized code can be found in [3] with 15% measured speedup on the function level.

    8+ bytes instructions

    We identified another front-end feature that was limiting performance. However, unlike the previous example, it was caused by a characteristic of the microarchitecture -- “The Silvermont microarchitecture can only decode one instruction per cycle if the instruction exceeds 8 bytes” [1].

    In this particular case, the mb_lpf_horizontal_edge_w_sse2_16 [4] code suffered from the heavy vector register pressure and multiple loads/stores to the stack, making operations with mem source necessary.

    Using rsp register added an additional SIB byte to the instruction encoding and generated a large number--exceeding 8 bytes--of instructions. Therefore, the frond-end throughput was limited (just slightly higher than 1 instruction decoded per cycle), and so couldn't achieve a good back-end utilization of 2 vector instructions per cycles.

    This issue was fixed by using an rbp register to address the stack, which does not add a SIB byte to the instruction and allowed us to achieve 20% function level speedup. Patch submission is still pending.

    4th prefix

    And the last, but not the least important, microarchitectual feature we had to work around in the code was the 3-cycle decoding delay dealing with instructions that have 4 or more prefixes. As you might know Silvermont architecture can decode up to 2 instructions per cycle, or up to 6 instructions in 3 cycles. Therefore, decoding just one instruction in 3 cycles quite often can create the case performance issues.

    Quite often a 4th prefix is added when any of the upper 8 xmm registers (xmm7-xmm15) are used with some of the vector instructions, as using those registers will add an extra REX prefix to the instruction. pmaddubsw instruction is a good example of such a case [5]. In particular, “pmaddubsw xmm1, xmm2” will result in the following encoding “66 0F 38 04 …”, and “pmaddubsw xmm1, xmm16” will add the REX prefix – “66 41 0F 38 04 …”

    We were able to achieve 25% speedup on the function level by limiting the vector registers usage for those particular instructions.

    Performance Results

    The overall results were outstanding. The team improved user-level performance by up to 16 percent (6.2 frames per second) in 64-bit mode and by about 12 percent (1.65 frames per second) in 32-bit mode. This testing included evaluation of 32-bit and 64-bit GCC and Intel® compilers, and concluded that the Intel compilers delivered the best optimizations by far for Intel® Atom™ processors. When you multiply this improvement by millions of viewers and thousands of videos, it is significant. The WebM team at Google also recognized this performance gain as extremely significant. Frank Gilligan, a Google engineering manager, responded to the team’s success: “Awesome. It looks good. I can’t wait to try everything out.” Testing against the future Intel Atom platforms, codenamed Goldmont and Tremont, the VP9 optimizations delivered additional gains.

    While the video decoder was already highly optimized on the Intel® Core™ processor, it wasn’t very efficient on Intel® Atom™ architecture. Now, watching YouTube content or video conferencing can lead to a better user experience with higher quality and no lag. This effort was also important because of the increasing number of YouTube users that will enjoy watching video on Intel® architecture-based devices. The team also identified and fixed possible performance issues on 64-bit Intel Atom platforms before anyone was able to experience it on the end-user devices.

    The success has proved durable. Our performance team delivered significant, long-lasting improvements in end-user experience. After meeting and exceeding goals on 32-bit Android, our team expanded our horizons and extended our scope to include the 64-bit environment in anticipation of 64-bit Android.

    About the Authors

    Tamar Levy and Ilya Albrekht are software engineers on the Client Platform Enabling Team in the Software and Services Group working with individual customers on projects for Windows* and Android media performance-enabling applications.

    Related References

    [1http://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf

    [2https://chromium.googlesource.com/webm/libvpx/+/v1.3.0/vp9/common/x86/vp9_subpixel_8t_ssse3.asm#778

    [3https://chromium.googlesource.com/webm/libvpx/+/v1.5.0/vpx_dsp/x86/vpx_subpixel_8t_ssse3.asm#364

    [4https://chromium.googlesource.com/webm/libvpx/+/v1.3.0/vp9/common/x86/vp9_loopfilter_intrin_sse2.c#373

    [5https://chromium.googlesource.com/webm/libvpx/+/v1.4.0/vp9/common/x86/vp9_subpixel_8t_intrin_ssse3.c#237

    [6https://software.intel.com/en-us/intel-stress-bitstreams-and-encoder/reviews

    [7https://software.intel.com/en-us/articles/video-quality-caliper-quick-overview

    [8http://www.webmproject.org/vp9

    [9http://www.tomsguide.com/us/what-is-vp9-4k-streaming,news-18221.html

    Viewing all 183 articles
    Browse latest View live


    <script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>