Quantcast
Channel: Android*
Viewing all 343 articles
Browse latest View live

Tutorial Cocos2d-x usando Windows* - Parte 1

$
0
0

Nesta série de tutoriais iremos demonstrar como criar um jogo simples usando o framework Cocos2d-x em um ambiente de desenvolvimento Windows*.

O que é o Cocos2d-x?


O Cocos2d-x é um framework multi-plataforma de desenvolvimento de jogos (e outros apps gráficos como livros interativos) baseado no cocos2d para iOS, mas que usa C++, Javascript ou Lua ao invés do Objective-C.

Uma das vantagens desse framework é permitir o desenvolvimento de jogos para diversas plataformas (Android*, iOS*, Win32*, Windows* Phone, Windows* 8, Mac*, Linux*, etc) mantendo apenas uma base de código (com algumas adaptações sendo feitas de uma plataforma para outra).

Ele é open-source sob a licença MIT License e seu código fonte pode ser encontrado aqui.

Para mais informações sobre o Cocos2d-x e sua documentação, acesse: http://www.cocos2d-x.org/

Criando seu primeiro game


1-  Faça o download da versão mais recente do framework no site e descompacte no seu ambiente de desenvolvimento. Para este tutorial foi utilizada a versão 2.2.2 e o framework foi descompactado na área de trabalho (C:\Users\felipe.pedroso\Desktop\cocos2d-x-2.2)

2- Para criar um novo projeto no cocos2d-x, iremos usar um script python (create_project.py) que cria toda a estrutura do projeto dentro da pasta aonde o framework foi descompactado. Caso não tenha o runtime do Python instalado, faça o download da versão 2.7.6 no seguinte link: http://www.python.org/download/.

3-  Abra o prompt de comando (cmd.exe) e execute os seguintes comandos:

-   Navegue até a pasta do script (é importante que o script create_project.py seja executado de dentro da pasta project-creator)
    
    cd C:\Users\felipe.pedroso\Desktop\cocos2d-x-2.2\tools\project-creator
    
-   Execute o script com seguinte comando:
    
    python create_project.py -project MyFirstGame -package com.example.myfirstgame -language cpp
    

Explicando os parâmetros:
    project: Nome do seu projeto/game
    package: Nome do pacote da sua aplicação (ex.: br.suaempresa.MyFirstGame)
    language: Linguagem de programação a ser utilizada (cpp, lua e javascript)

Obs.: para executar o comando 'python' na linha de comando, adicione a pasta aonde o Python foi instalado na variável de ambiente Path

-   Se tudo funcionar corretamente, seu projeto será criado na pasta projects, dentro do diretório onde o framework foi descompactado.

O projeto criado contém o código base do jogo (Classes), os recursos (imagens, áudio, etc) e projetos para cada uma das plataformas suportadas pelo framework.

Compilando para Win32 (Windows* 7 ou Windows* 8 modo desktop)


Requisitos:

Dentro do diretório do projeto, abra o arquivo MyFirstGame.sln que está na pasta proj.win32 com o Visual Studio.

Compile o projeto pressionando F6 (ou menu Build -> Build Solution) e execute o projeto pressionando F5 (ou menu Debug->Start Debugging).

Se tudo der certo, você verá a seguinte janela:

Compilando para Windows* 8 (Windows* Store App)


Requisitos:

Para compilar o projeto como uma Windows* Store App, abra o arquivo MyFirstGame.sln da pasta proj.winrt e compile da mesma maneira do projeto Win32.

Após compilar e rodar, você verá a seguinte tela:

Obs.: a versão do cocos2d-x utilizada no tutorial não funcionou no Windows* 8.1

Compilando para Android*


Requisitos

Da mesma forma que o Python foi adicionado no Path do Windows*, adicione os diretórios tools e platform-tools do Android SDK,o diretório raiz do NDK e o diretório bin do Apache Ant para poder usar os comandos para fazer build do app.

Abra um novo prompt de comando (cmd.exe) e execute os seguintes comandos para configurar as variáveis de ambiente necessárias para a compilação do app Android:

    set COCOS2DX_ROOT=C:\Users\felipe.pedroso\Desktop\cocos2d-x-2.2
    set NDK_TOOLCHAIN_VERSION=4.8
    set NDK_MODULE_PATH=%COCOS2DX_ROOT%;%COCOS2DX_ROOT%\cocos2dx\platform\third_party\android\prebuilt

    
Explicando as variáveis:

    COCOS2DX_ROOT: diretório aonde o cocos2d-x foi extraído
    NDK_TOOLCHAIN_VERSION: versão do toolchain do NDK que será utilizado para compilar o projeto
    NDK_MODULE_PATH: Módulos que devem ser incluídos na compilação do NDK. No caso do exemplo, estamos utilizando os módulos pré-compilados do cocos2d-x

Com as variáveis de ambiente configuradas, navegue até o diretório do projeto:

    cd C:\Users\felipe.pedroso\Desktop\cocos2d-x-2.2\projects\MyFirstGame\proj.android

Copie os resources do jogo (imagens, sons, etc) para a pasta assets:

    rmdir /S /Q assets
    mkdir assets
    xcopy /E ..\Resources .\assets

Execute o seguinte comando para compilar os módulos nativos:

    ndk-build.cmd -C . APP_ABI="armeabi armeabi-v7a x86"

O comando irá gerar as bibliotecas nativas para três arquiteturas diferentes: ARM, ARM-NEON e x86. Isso permitirá que seu jogo rode em diversas arquiteturas aproveitando o que elas oferecem de melhor. .Após finalizar a compilação dos módulos nativos, compile o app Android com o comando ant:

    ant debug


    
Agora para instalar o aplicativo em um device ou emulador use o comando:

    adb install -r bin\MyFirstGame.apk

Depois é só abrir o app:

Pronto, agora seu jogo já pode rodar em pelo menos três plataformas: Android* (em três arquiteturas), Windows* 7 e Windows* 8! Na próxima parte iremos falar sobre como o framework funciona, como adicionar um elemento na tela e como fazer ele se movimentar.

Até a próxima!

* Other names and brands may be claimed as the property of other

  • cocos2d-x
  • mobile game development
  • Desenvolvedores
  • Parceiros
  • Professores
  • Estudantes
  • Android*
  • Microsoft Windows* (XP, Vista, 7)
  • Microsoft Windows* 8
  • Android*
  • Windows*
  • C/C++
  • Principiante
  • Desenvolvimento de jogos
  • Laptop
  • Telefone
  • Tablet
  • Desktop
  • URL
  • Para começar

  • Develop HTML5 chart applications for Android and Win8 devices

    $
    0
    0

    Abstract

    Presenting charts is one of the key components in business applications, and many of customers trend to use them in mobile devices. Therefore, how to make the charts application keep same performance in both desktop and mobile platform is important. In this article, we will introduce a cross-platform HTML5 library called ichartjs, which could build charts applications easily on both Android devices and Windows 8 ultrabooks/tablets. It supports most of popular charts and graphics, such as pie charts, line graph, area chart, column diagram, bar chart, etc. Besides, all of them could be developed and packaged to hybrid applications (Android, iOS, WP, Win8, Web) with Intel XDK Tools.

     

    iChartJS architecture

    iChartJS is a popular charts library to build HTML5 charts application, it supports Android, iOS and Windows. Besides, the application could keep same layout among different platforms. It is licensed under Apache 2.0.

    Elelemt: the root class, it defines some configure information

    Painter: Root class of graph, all canvas painting functions are defined in this class.

    Chart: All configureations about charts are defined in this class.

    Component: Parent class of components in charts.

    Html: Including all classes, which are built in html, defined basic css style and animation.

    Quick Tutorial of Bar Column

    Let’s begin with a quick column diagram to know the basic usage of iChartJS

    1.    include iChartJS in your html file.

    <script type="text/javascript" src="ichart-1.2.min.js"></script>

    2.    Define your source data in JavaScript, in this demo, we defined 10 sets of source data.

    var data = [

    {name : 'H',value : 7,color:'#a5c2d5'},

    {name : 'E',value : 5,color:'#cbab4f'},

    {name : 'L',value : 12,color:'#76a871'},

    {name : 'L',value : 12,color:'#76a871'},

    {name : 'O',value : 15,color:'#a56f8f'},

    {name : 'W',value : 13,color:'#c12c44'},

    {name : 'O',value : 15,color:'#a56f8f'},

    {name : 'R',value : 18,color:'#9f7961'},

    {name : 'L',value : 12,color:'#76a871'},

    {name : 'D',value : 4,color:'#6f83a5'}

    ];

    $(function(){

    new iChart.Column2D({

    render : 'canvasDiv', //Render object

    data: data,//Binding source data

    title :{ text:'Hello World\'s Height In Alphabet'}, //set header

    width : 800, //set width

    height : 400, //set height

    coordinate:{ //set coordinate

    scale:[{

    position:'left', //values on the left

    start_scale:0, //start value

    end_scale:26, //end value

    scale_space:2, //separation distance

    listeners:{

    parseText:function(t,x,y){

    return {text:t+" CM"}//customized value

    }

    }

    }]

    }

    }).draw();//render the graph

    });

    4.    The last step is create a Canvas object in HTML .

    <div id=”canvasDiv”></div>

    Open your browser, the bar diagram is ready as below.

    If you need the chart to auto fit the screen, you need to change the height and with value line to fit: true. And then open it in you mobile devices, it could auto fit your devices’ screen resolution.

    Build Pie Chart

    Pie charts are mostly used to display part and the overall relationship. It could highlight the proportion of data, but not suit to display large amount of data.

    In the pie chart, three o’clock direction is set as default direction. However, user could also modify them from the parameter offset_angle. The positive value represents clockwise migration, while the negative value represents anticlockwise migration.

    For example, if we want to set the starting angle at 12 o 'clock direction, source codes are set as follows:

    new iChart.Pie2D({

    offset_angle :-90

    });

    In some special situation, you may also want to set an appropriate radius. Don’t worry; radius setting is available at all situation. Let’s try to set the radius to 120px by the following codes:

    new iChart.Pie2D({

    radius:120

    });

    The next one is about setting label to meet the special needs in visual. For example, in some cases, we may need to remove extended label in small chart. Mini label is the right choice, you just need to open the switch of mini label by setting true:

    mini_label: true.

    mini_label _threshold_angle is designed to settting the minimum angle of mini label in case of display conflicts.

    A sample pie chart with mini label source codes:

    new iChart.Pie2D({

    sub_option:{

    mini_label : true,

    mini_label_threshold_angle : 30 ,

    label:{

    fontsize:16,

    color:'#FFFFFF'

    }

    }

    });

    The event in the pie chart is determined by components in this graph, such as fan, illustrations, and labels. A sample of setting events in fan area is showed as below:

    new iChart.Pie2D({

    sub_option:{

    listeners:{

    click:function(c,e){

    // …

    }

    }

    }

    });

    Maybe you also need to separate the distance of each item, modifying the separate_angle parameter could achieve your goal. The range of angle could be set form 0 to 90, with default value of 30. 

    If we set the angle to 60 by the below source codes, and the visual effect is showed as below:

    new iChart.Pie2D({

    separate_angle:60

    });

     

    Build Line Graph

    If you want to build line graph, it is also piece of cake with iChartJS and not need to worry about cross-platform performance distance. Firstly, you need to include iChartJS in HTML file as below:

    <script type="text/javascript" src="ichart-1.2.min.js"></script>

    And then set your data source in format:

    var data = [

    {name : 'H',value : 7,color:'#a5c2d5'},

    {name : 'E',value : 5,color:'#cbab4f'},

    ……

    ];

    The next step is create a line graph object in JavaScript:

    new iChart.LineBasic2D ({

    sub_option{

    // …

    }

    });

    You may have found that there are plenty of parameters setting in sub_option. In this example, we set the point_size to 8, hollow to false, smooth to true. The source codes are showed as below:

    new iChart.LineBasic2D ({

    sub_option:{

    smooth : true,

    point_size:8,

    hollow: false

    }

    });

    Now, let’s see the visual effect of line graph:

    There are still many other fancy charts could be built with iChartJS, which are fully support both Android and Windows platform. At the last , I would like to show some examples, which are built with iChartJS.

    Summary

    In this article, we introduced a popular cross-platform HTML5 charts library called ichartjs, presented quick tutorials about how to build column diagram, pie chart and line graph. There are still many other types of charts in this library, you could find them from www.icharjs.com. Besides, if you want to develop android or windows 8 chart applications, Intel XDK is a good option for you. ichartjs run perfect with Intel XDK. Go to xdk-software.intel.com, there are plenty of demos and tutorials about building HTML5 applications with external libraries.

    Reference

    1.    www.ichartjs.com

    2.    xdk-software.intel.com

    3.    http://www.ichartjs.com/docs/en/

    4.    http://www.ichartjs.com/samples/index.html

  • HTML5 App XDK
  • Desenvolvedores
  • Estudantes
  • Android*
  • Microsoft Windows* 8
  • HTML5
  • HTML5
  • Principiante
  • Intel® XDK
  • URL
  • Sample Code: Media Sample for Android* Advanced Media Player

    $
    0
    0

    By Dmitry Rizshkov

    Media Sample – Android* Advanced Media Player

    This sample demonstrates the more advanced media interfaces that Android developers can take advantage of. For applications requiring more control over the media pipeline, this sample is an excellent starting point. The modularity of this sample lends itself to customization by developers. Transport controls are handled within the MediaEngine class; audio playback is handled by the MediaAudioThread class; video playback is handled by the MediaVideoThread class; and transport control UI is handled by the PlaybackToolbar class.

    To build this sample code, you need to have the Android development environment installed. Please refer to this link for more details: http://developer.android.com/index.html

    All Advanced Media Player source code is provided to users under the following license:

    /* Copyright © 2014, Intel Corporation
    *
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions are met:
    *
    * - Redistributions of source code must retain the above copyright notice,
    * this list of conditions and the following disclaimer.
    * - Redistributions in binary form must reproduce the above copyright notice,
    * this list of conditions and the following disclaimer in the documentation
    * and/or other materials provided with the distribution.
    * - Neither the name of Intel Corporation nor the names of its contributors
    * may be used to endorse or promote products derived from this software
    * without specific prior written permission.

    *
    * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    * POSSIBILITY OF SUCH DAMAGE.
    *
    */

  • media player
  • Desenvolvedores
  • Android*
  • Android*
  • Java*
  • URL
  • Exemplo de código
  • Code Sample: Media Sample for Android* Basic Touch Media Player

    $
    0
    0

    By Lana Lindberg

    Media Sample – Android* Basic Touch Media Player

    This sample demonstrates the basic interfaces available within Android that allow developers to playback various locally stored media files. It also illustrates a basic approach to add touch capabilities to an application that already uses MediaController interfaces. VideoView enables the display of video, while the MediaController allows users to control the playback, pause, fast forward, and rewind through a basic transport interface. The transport interface exposed by MediaController can be hidden. In this application we hide the default MediaController transport and supplement the application with a rudimentary touch interface enabled by handling onTouchEvent() messages.

    To build this sample code, you need to have the Android development environment installed. Please refer to this link for more details: http://developer.android.com/index.html

    All Basic Touch Media Player source code is provided to users under the following license:

    /* Copyright © 2014, Intel Corporation
    *
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions are met:
    *
    * - Redistributions of source code must retain the above copyright notice,
    * this list of conditions and the following disclaimer.
    * - Redistributions in binary form must reproduce the above copyright notice,
    * this list of conditions and the following disclaimer in the documentation
    * and/or other materials provided with the distribution.
    * - Neither the name of Intel Corporation nor the names of its contributors
    * may be used to endorse or promote products derived from this software
    * without specific prior written permission.

    *
    * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    * POSSIBILITY OF SUCH DAMAGE.
    *
    */

  • media player
  • Desenvolvedores
  • Android*
  • Android*
  • Java*
  • URL
  • Exemplo de código
  • Sample Code: Media Sample for Android* Basic Media Player

    $
    0
    0

    By Mark Liu

    Media Sample – Android* Basic Media Player

    This sample demonstrates the basic interfaces available within Android that allow developers to playback various locally stored media files. It takes advantage of the VideoView and MediaController interfaces. VideoView enables the display of video, while the MediaController allows users to control the playback, pause, fast forward, and rewind through a basic transport interface.

    To build this sample code, you need to have the Android development environment installed. Please refer to this link for more details: http://developer.android.com/index.html

    All Basic Media Player source code is provided to users under the following license:

    /* Copyright © 2014, Intel Corporation
    *
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions are met:
    *
    * - Redistributions of source code must retain the above copyright notice,
    * this list of conditions and the following disclaimer.
    * - Redistributions in binary form must reproduce the above copyright notice,
    * this list of conditions and the following disclaimer in the documentation
    * and/or other materials provided with the distribution.
    * - Neither the name of Intel Corporation nor the names of its contributors
    * may be used to endorse or promote products derived from this software
    * without specific prior written permission.

    *
    * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    * POSSIBILITY OF SUCH DAMAGE.
    *
    */

  • media player
  • Desenvolvedores
  • Android*
  • Android*
  • Java*
  • URL
  • Exemplo de código
  • Sample Code: Data Encryption Application

    $
    0
    0

    Download as PDF

    Download sample code

    Christopher Bird, Software Applications Engineers

    Application Origination:
    Intel SSG

    Introduction

    Encryption is important because it allows you to securely protect data that you don't want anyone else to have access to. Encryption has been a trending topic in the security community. As more mobile devices store valuable information than ever before, encryption has become crucial to ensure information security.

    This paper introduces data encryption APIs that are available through either Java* or OpenSSL*. Both solutions work on the Android* OS.

    We recommend that you try out the features and compile the code as you read through the paper.

    Data Encryption Code and Explanations

    If you want to encrypt data on Android, you have two options: Java Crypto API and OpenSSL API. We will show you how to encrypt data using both ways.

    Java Crypto API

    Using Java Crypto API on Android is very straightforward.  First, you will need to generate a key for the encryption. There is a KeyGenerator class in the javax.crypto package that can do this for you.

    	mKey = null;
    	try {
    		kgen = KeyGenerator.getInstance("AES");
    		mKey = kgen.generateKey();
    
    	} catch (NoSuchAlgorithmException e) {
    		e.printStackTrace();
    	}
    
    

     

    Then you can use the generated key to encrypt the data file. This can be done by feeding chunks of bytes to an AES Cipher created by javax.crypto.

    // open stream to read origFilepath. We are going to save encrypted contents to outfile
    	InputStream fis = new FileInputStream(origFilepath);		
    	File outfile = new File(encFilepath);
    	int read = 0;
    	if (!outfile.exists())
    		outfile.createNewFile();
    		
    	FileOutputStream encfos = new FileOutputStream(outfile);
    	// Create Cipher using "AES" provider
    	Cipher encipher = Cipher.getInstance("AES");
    	encipher.init(Cipher.ENCRYPT_MODE, mKey);
    	CipherOutputStream cos = new CipherOutputStream(encfos, encipher);
    		
    	// capture time it takes to encrypt file
    	start = System.nanoTime();
    	Log.d(TAG, String.valueOf(start));
    		
    	byte[] block = new byte[mBlocksize];
    		
    	while ((read = fis.read(block,0,mBlocksize)) != -1) {
    		cos.write(block,0, read);
    	}
    	cos.close();
    	stop = System.nanoTime();
    		
    	Log.d(TAG, String.valueOf(stop));
    	seconds = (stop - start) / 1000000;// for milliseconds
    	Log.d(TAG, String.valueOf(seconds));
    		
    	fis.close();
    
    

     

    OpenSSL API

    Encrypting data in OpenSSL on Android requires writing native C code that can be accessed in Java through JNI calls. It requires more work, but you will get better performance in return. 

    First, let’s generate the key and the iv.

    unsigned char cKeyBuffer[KEYSIZE/sizeof(unsigned char)];
    unsigned char iv[] = "01234567890123456";
    int opensslIsSeeded = 0;
    if (!opensslIsSeeded) {
    	if (!RAND_load_file("/dev/urandom", seedbytes)) {
    		return -1;
    	}
    	opensslIsSeeded = 1;
    }
    
    if (!RAND_bytes((unsigned char *)cKeyBuffer, KEYSIZE )) {
    }
    
    

     

    Then, we can use the generated key (cKeyBuffer) to encrypt a file. Initialize EVP by feeding it your key and iv. Then feed chunks of bytes to the EVP_EncryptUpdate function. The final chunk of bytes from your file will need to be fed to the EVP_EncryptFinal_ex function.

    
    if (!(EVP_EncryptInit_ex(e_ctx, EVP_aes_256_cbc(), NULL, cKeyBuffer, iv ))) {
    	ret = -1;
    	printf( "ERROR: EVP_ENCRYPTINIT_EXn");
    }
    	
    // go through file, and encrypt
    if ( orig_file != NULL ) {
       	origData = new unsigned char[aes_blocksize];
        	encData = new unsigned char[aes_blocksize+EVP_CIPHER_CTX_block_size(e_ctx)]; // potential for encryption to be 16 bytes longer than original
    
    	printf( "Encoding file: %sn", filename);
    
    	bytesread = fread(origData, 1, aes_blocksize, orig_file);
    	// read bytes from file, then send to cipher
    	while ( bytesread ) {
    
    
    		if (!(EVP_EncryptUpdate(e_ctx, encData, &len, origData, bytesread))) {
    			ret = -1;
    			printf( "ERROR: EVP_ENCRYPTUPDATEn");
    		}
    		encData_len = len;
    
    		fwrite(encData, 1, encData_len, enc_file );
    		// read more bytes
    		bytesread = fread(origData, 1, aes_blocksize, orig_file);
    	}
    	// last step encryption
    	if (!(EVP_EncryptFinal_ex(e_ctx, encData, &len))) {
    		ret = -1;
    		printf( "ERROR: EVP_ENCRYPTFINAL_EXn");
    	}
    	encData_len = len;
    
    	fwrite(encData, 1, encData_len, enc_file );
    
    	// free cipher
    	EVP_CIPHER_CTX_free(e_ctx);
    
    

     

    Conclusion

    By implementing code like the samples described in this paper, you can quickly learn how to  use both Java Crypto API and OpenSSL API to encrypt data on Intel® processor-based platforms running Android.

    About the author

    Christopher Bird is a member of the Intel Software and Solutions Group (SSG), Developer Relations Division, Intel® Atom™ Processor Innovative Technologies Engineering team. 

    Notices

    INFORMATION IN THIS DOCUMENT IS PROVIDED IN CONNECTION WITH INTEL PRODUCTS. NO LICENSE, EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE, TO ANY INTELLECTUAL PROPERTY RIGHTS IS GRANTED BY THIS DOCUMENT. EXCEPT AS PROVIDED IN INTEL'S TERMS AND CONDITIONS OF SALE FOR SUCH PRODUCTS, INTEL ASSUMES NO LIABILITY WHATSOEVER AND INTEL DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY, RELATING TO SALE AND/OR USE OF INTEL PRODUCTS INCLUDING LIABILITY OR WARRANTIES RELATING TO FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR INFRINGEMENT OF ANY PATENT, COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT.

    UNLESS OTHERWISE AGREED IN WRITING BY INTEL, THE INTEL PRODUCTS ARE NOT DESIGNED NOR INTENDED FOR ANY APPLICATION IN WHICH THE FAILURE OF THE INTEL PRODUCT COULD CREATE A SITUATION WHERE PERSONAL INJURY OR DEATH MAY OCCUR.

    Intel may make changes to specifications and product descriptions at any time, without notice. Designers must not rely on the absence or characteristics of any features or instructions marked "reserved" or "undefined." Intel reserves these for future definition and shall have no responsibility whatsoever for conflicts or incompatibilities arising from future changes to them. The information here is subject to change without notice. Do not finalize a design with this information.

    The products described in this document may contain design defects or errors known as errata which may cause the product to deviate from published specifications. Current characterized errata are available on request.

    Contact your local Intel sales office or your distributor to obtain the latest specifications and before placing your product order.

    Copies of documents which have an order number and are referenced in this document, or other Intel literature, may be obtained by calling 1-800-548-4725, or go to: http://www.intel.com/design/literature.htm

    Software and workloads used in performance tests may have been optimized for performance only on Intel microprocessors. Performance tests, such as SYSmark* and MobileMark*, are measured using specific computer systems, components, software, operations, and functions. Any change to any of those factors may cause the results to vary. You should consult other information and performance tests to assist you in fully evaluating your contemplated purchases, including the performance of that product when combined with other products.

    Any software source code reprinted in this document is furnished under a software license and may only be used or copied in accordance with the terms of that license.

    Intel, the Intel logo, and Atom are trademarks of Intel Corporation in the US and/or other countries.

    Copyright © 2014 Intel Corporation. All rights reserved.

    *Other names and brands may be claimed as the property of others.

  • Desenvolvedores
  • Android*
  • Android*
  • URL
  • Sample Code: One Time Password (OTP) Demo

    $
    0
    0

    Download as PDF

    Download source code

    Peng Wang, Software Applications Engineer

    Application Origination:
    Intel SSG

    Introduction

    Traditionally, two-factor authentication uses a one-time password (OTP), which combines something the user knows (a username and password) and something the user has (typically, a token or key fob that produces a six-digit number, valid only for a short period of time and available on demand).

    If your business is already using two-factor authentication, then you are also familiar with the various issues around token usability and logistics. Replacing lost or broken tokens and users mistyping their one-time passwords are just two of the headaches currently affecting help desks and IT departments. Intel® Identity Protection Technology (Intel® IPT) with OTP is a built-in hardware token (of your security vendor choice) that negates the need for a separate physical token, thus simplifying the two-factor VPN log-in process for a seamless experience with virtually no delays.

    The purpose of this paper is to provide a high level overview of the one-time password (OTP) functionalities and show how to use the OTP APIs in Android*.

    Code and Explanations

    OTP has three major functionalities: OTP provisioning, OTP generation, and OTP verification.  There are also APIs for querying OTP capability and the OTP version on the system.

    OTP Provisioning

    InvokeIPTProv extends the AsyncTask to execute the provisioning in the background. It first creates the security service (Provision Service) and then starts the provisioning process.

    @Override
    protected Void doInBackground(Void... params) {
    	ChaabiProvision prov = new ChaabiProvision();
    	try {
    		prov.execute().get(PROV_MAX_TIMEOUT, TimeUnit.MILLISECONDS);
    	} catch (InterruptedException e) {
    		error = "Provisioning failed: " + e.getClass().getName() + ": "
    				+ e.getLocalizedMessage();
    		e.printStackTrace();
    	} catch (ExecutionException e) {
    		error = "Provisioning failed: " + e.getClass().getName() + ": "
    				+ e.getLocalizedMessage();
    		e.printStackTrace();
    	} catch (TimeoutException e) {
    		error = "Provisioning failed: " + e.getClass().getName() + ": "
    				+ e.getLocalizedMessage();
    		e.printStackTrace();
    	}
    	return null;
    }
    
    

    OTP Generation  

    Before we start generating the OTP, we need to check if the device has already successfully completed the provisioning process.

    // Read token if exists
    if (!readData()) {
    	tvOTPGenerate
    			.setText("OTP generation failed: No token exists. Please do provisioning.");
    	return;
    }
    
    

    Then we can invoke the Async call to generate the OTP.

    boolean invokeResyncGenerateOTP(IPTWrapper obj) {
    	try {
    		// Send request to the server for resync message and process
    		// the received resync message
    		InvokeIPTResync ipt_obj = new InvokeIPTResync();
    		boolean status = ipt_obj.execute().get();
    		if (status) {
    
    			// Processes the server resync message
    			obj.ProcessResyncMessage(encrToken_b64, serverResyncMessage);
    
    			// Invoke OTP generation again
    			// Check if token is of type OCRA
    			if (tokenInfo
    					.equalsIgnoreCase(OTPDemoActivity.OCRA_TOKEN_INFO)) {
    				invokeGenerateOTP(obj, true);
    			} else {
    				invokeGenerateOTP(obj, false);
    			}
    			displayOTP();
    			progressDialog.dismiss();
    		} else {
    			String error = "Receive server resync message failed.";
    			tvOTPGenerate.setText(error);
    			progressDialog.dismiss();
    			OTPDemoActivity.OTP = null;
    			return false;
    		}
    	} catch (IhaException e) {
    		String error = "OTP generation failed. Message: "
    				+ e.getLocalizedMessage() + " Error code: " + e.GetError();
    		tvOTPGenerate.setText(error);
    		progressDialog.dismiss();
    		OTPDemoActivity.OTP = null;
    		return false;
    	} catch (Exception e) {
    		String error = "OTP generation failed: " + e.getClass().getName()
    				+ ": " + e.getLocalizedMessage();
    		tvOTPGenerate.setText(error);
    		progressDialog.dismiss();
    		OTPDemoActivity.OTP = null;
    		return false;
    	}
    	return true;
    }
    
    

    OTP Verification

    Once the OTP is generated, we can then check if it is valid.

    	ChaabiOTPVerify otp_ver = new ChaabiOTPVerify();
    	try {
    		otp_ver.execute()
    				.get(OTP_VERIFY_TIMEOUT, TimeUnit.MILLISECONDS);
    	} catch (InterruptedException e) {
    		error = "OTP verification failed: " + e.getClass().getName()
    				+ ": " + e.getLocalizedMessage();
    		e.printStackTrace();
    	} catch (ExecutionException e) {
    		error = "OTP verification failed: " + e.getClass().getName()
    				+ ": " + e.getLocalizedMessage();
    		e.printStackTrace();
    	} catch (TimeoutException e) {
    		error = "OTP verification failed: " + e.getClass().getName()
    				+ ": " + e.getLocalizedMessage();
    		e.printStackTrace();
    	}
    	return null;	} catch (JSONException e) {
    		error = e.getClass().getName() + ": " + e.getLocalizedMessage();
    		status = false;
    		e.printStackTrace();
    	} catch (UnsupportedEncodingException e) {
    		error = e.getClass().getName() + ": " + e.getLocalizedMessage();
    		status = false;
    		e.printStackTrace();
    	} catch (ClientProtocolException e) {
    		error = e.getClass().getName() + ": " + e.getLocalizedMessage();
    		status = false;
    		e.printStackTrace();
    	} catch (IOException e) {
    		error = e.getClass().getName() + ": " + e.getLocalizedMessage();
    		status = false;
    		e.printStackTrace();
    	}
    	Log.v(LOG_TAG, "Return results: " + status);
    	return status;
    }
    
    

    Query OTP Capability

    Built-in, hardware-based OTP is not available on all mobile devices, so it would be helpful to first query the system if the OTP capability is available.

    private boolean isOTPCapable(){
    	try {
    		IPTWrapper caps = new IPTWrapper();
    		String cap = caps.GetCapabilities();
    		displayMessage("Capabilities: " + cap);
    		return true; 
    	} catch (IhaException e) {
    		String error = "GetCapabilities() failed. Message: "
    				+ e.getLocalizedMessage() + " Error code: "
    				+ e.GetError();
    		notifyUser("Failed: " + error);
    		return false;
    	} catch (Exception e) {
    		String error = "GetCapabilities() failed: "
    				+ e.getClass().getName() + ": "
    				+ e.getLocalizedMessage();
    		notifyUser("Failed: " + error);
    		return false;
    	}
    }
    
    

    Conclusion

    By implementing code like the samples described in this paper, you can quickly learn how to use Intel® IPT with one-time password APIs to utilize hardware-based OTP on Intel® processor-based platforms running Android.

    About the author

    Peng Wang is a member of the Intel® Software and Solutions Group (SSG), Developer Relations Division, Intel® Atom™ Processor High Touch Software Enabling team. Before joining SSG, Peng was leading the integration and validation team for the Ultra Mobile Group. 

     

    Notices

    INFORMATION IN THIS DOCUMENT IS PROVIDED IN CONNECTION WITH INTEL PRODUCTS. NO LICENSE, EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE, TO ANY INTELLECTUAL PROPERTY RIGHTS IS GRANTED BY THIS DOCUMENT. EXCEPT AS PROVIDED IN INTEL'S TERMS AND CONDITIONS OF SALE FOR SUCH PRODUCTS, INTEL ASSUMES NO LIABILITY WHATSOEVER AND INTEL DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY, RELATING TO SALE AND/OR USE OF INTEL PRODUCTS INCLUDING LIABILITY OR WARRANTIES RELATING TO FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR INFRINGEMENT OF ANY PATENT, COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT.

    UNLESS OTHERWISE AGREED IN WRITING BY INTEL, THE INTEL PRODUCTS ARE NOT DESIGNED NOR INTENDED FOR ANY APPLICATION IN WHICH THE FAILURE OF THE INTEL PRODUCT COULD CREATE A SITUATION WHERE PERSONAL INJURY OR DEATH MAY OCCUR.

    Intel may make changes to specifications and product descriptions at any time, without notice. Designers must not rely on the absence or characteristics of any features or instructions marked "reserved" or "undefined." Intel reserves these for future definition and shall have no responsibility whatsoever for conflicts or incompatibilities arising from future changes to them. The information here is subject to change without notice. Do not finalize a design with this information.

    The products described in this document may contain design defects or errors known as errata which may cause the product to deviate from published specifications. Current characterized errata are available on request.

    Contact your local Intel sales office or your distributor to obtain the latest specifications and before placing your product order.

    Copies of documents which have an order number and are referenced in this document, or other Intel literature, may be obtained by calling 1-800-548-4725, or go to: http://www.intel.com/design/literature.htm

    Software and workloads used in performance tests may have been optimized for performance only on Intel microprocessors. Performance tests, such as SYSmark* and MobileMark*, are measured using specific computer systems, components, software, operations, and functions. Any change to any of those factors may cause the results to vary. You should consult other information and performance tests to assist you in fully evaluating your contemplated purchases, including the performance of that product when combined with other products.

    Any software source code reprinted in this document is furnished under a software license and may only be used or copied in accordance with the terms of that license.

    Intel, the Intel logo, and Atom are trademarks of Intel Corporation in the US and/or other countries.

    Copyright © 2014 Intel Corporation. All rights reserved.

    *Other names and brands may be claimed as the property of others.

  • Desenvolvedores
  • Android*
  • Android*
  • URL
  • Meshcentral.com - Improved Android Agent

    $
    0
    0

    Android is an increasingly important operating system for a wide array of usages and Meshcentral is making sure administrators can remotely monitor and manage Android devices anywhere over the Internet. We manage all Android devices but make sure we take full advantage of Intel platform features. A few days back we updated the Android Mesh agent on Google Play. Among the many improvements made by my colleague Rick Edgecombe, two stand out:

    • Remote Input. When installing the Mesh agent on a rooted Android device, the agent has built-in remote desktop capability. Until now, you could see the display but could not interact with it. In this new agent, Rick creates a new emulated input device that generates both touch and keyboard input. The administrator’s mouse and keys are sent over the Internet and relayed thru this new input device. The result is full two-way control over an Android device. While getting a virtual input device to show up on Android has been done before, it’s certainly very technical and Rick did a wonderful job releasing this feature on Google Play for the world to use.
    • Remote Terminal. Up until now Meshcentral has had remote VT100 shell terminal support on all devices except Android. This is now fixed. Rick got the Mesh Agent to launch a new command prompt shell within the Android device and relay the input and output to the network. Administrators can now get command shell access to Android devices over the Internet and perform administrative commands that could only be done this way. It also allows administrators to automate actions and scripts.

    These two new features make the Mesh Android agent increasingly capable. The features add to the existing remote file access and remote management features already present and makes it much easier to fully manage Android devices over the Internet. Google Play will automatically update the agent on existing installations.

    You can see existing videos about the Android Mesh Android Agent on YouTube here and here.

    Enjoy!
    Ylian
    meshcentral.com

    Mesh Agent for Android features & connectivity breakdown.

    Screen shot of a rooted Android cell phone using CyanogenMod.
    The mesh agent makes a virtual input device show up during remote desktop sessions.

  • Mesh
  • MeshCentral
  • MeshCentral.com
  • p2p
  • android
  • Terminal
  • desktop
  • Remote Terminal
  • Remote Desktop
  • Ylian
  • Rick
  • Remote Input
  • Imagem do ícone: 

  • Computação em nuvem
  • Código aberto
  • Ferramentas de desenvolvimento para Android
  • Android*
  • Laptop
  • Telefone
  • Tablet
  • Desenvolvedores
  • Parceiros
  • Professores
  • Estudantes
  • Android*

  • The Concept of the Single Touch Joystick

    $
    0
    0

    By Ron Fosner and Alex Moore

    Hello, I’m Ron, and a few months ago I had the opportunity to lead an Android*/OpenGL ES* training. I not only wanted to have the class work on a graphics program that was practical but also informative and entertaining. Alex Moore had written a post on AltDevBlogADay about a unique single touch joystick implementation (see references), and I was struck with both the creativity and utility of the input gizmo he had created. I decided that for the training project we’d tackle implementing Alex’s joystick. It is a fun app to write and as well as a good introduction on how to convert touch input into movement in a 3D scene. Implementing the gizmo was an excellent introduction to processing touch input and creatively converting input into a complex control mechanism with just a little effort.

    Because of the positive feedback I received from that training, I decided to share the single touch joystick app with a larger audience. We think there’s a great opportunity to break some new ground for user input through touch interfaces. So I contacted Alex and he graciously agreed to help co-author this article. Alex will be sharing his ideas on the concept and history of the single touch joystick, while I’ll be discussing how we implemented it and how you might extend these ideas even further. Now let’s let Alex give some background on the idea of the Single Touch Joystick.

    Where the Concept Came From

     

    The idea behind single touch joystick stemmed from playing a few first and third person games on my Apple iPad* and feeling very constricted when interacting with them. Our mobile devices are powerful enough now to display rich, fully realized 3D worlds, but the lack of physical buttons forms a significant barrier for playing certain types of games. On the other hand, touch excels at creating great experiences for games that are tailored to it, so it seemed logical to me to investigate if there was an innovative way it could be used for a first person game.

    To start, I listed the most limiting factors with the current de-facto control method for first person games on touch: twin virtual joysticks. After researching popular games I distilled it down to the following two points:

    1. Due to the way gamers usually hold touch devices, only their thumbs are free. Twin virtual sticks require both thumbs to be used simultaneously, effectively rendering it impossible to do any other action without suddenly losing some level of control over your character.
    2. Gamers’ thumbs obscure the representation of the sticks on the screen, and as there is no haptic feedback (yet), it becomes very difficult to accurately position their thumbs.

    In addition to these, I wanted to try and develop something that could easily adapt to left-handed players, and also people who only have the use of one hand. The main motivation for this concept was the niggling feeling that there must be something better than just trying to copy the control method from a console controller, which in itself is often regarded as second best to using a keyboard and mouse.

    Developing the Idea

    After doing the research into the flaws of current implementations, I started to look at what you actually do when you’re playing a first or third person game on a PC or console, with the aim of trying to understand what any new system needs to achieve.

    If you watch a novice playing these types of game, it very quickly emerges that they often move to a position, then adjust their view, then move to another position. They rarely do both actions at once, whereas experienced players flow, seamlessly integrating movement and looking together.

    Look further though and you’ll notice another trend: once a player moves off in a direction, they’ll often carry on in that direction and just use the look axis to adjust where they’re heading. If they want to switch movement direction, say from forwards to sidestepping, it is usually very purposeful. Realizing this led me to the inner / outer circle concept: once a player has set off in a direction, can you then assume the player wants to carry on in that direction?

    I believed the answer is usually yes, so I drafted a design and then did a quick prototype. I was surprised at how good the initial tests felt and continued to refine it. After showing the concept to a few friends and getting a good response, I decided to dedicate a few days to really trying to get a polished mechanic together.

    The additional steps taken from the first prototype to the current version were all small iterations. I added the central HUD overlay so you can see what you’re doing and the direction arrows to further strengthen the message to the player as to what the system is doing (a good friend gave me the idea of illuminating the direction the player is rotating in).

    I hit a few dead ends too. One earlier version allowed you to start touching anywhere — which felt great — but prevented you from being able to rotate on the spot. I also tried reversing the circles so you rotated before moving, but that felt very odd indeed. Now Ron will discuss the details of how one can implement the idea.

    Implementing the Idea

    Implementation involves two steps: rendering the gizmo with the current state of the gizmo and manipulating the viewing matrix to reflect the state of the gizmo. The gizmo is modal, meaning it has two states that the user can transition between.

    Initially the gizmo is just a movement joystick. The user moves the virtual joystick vertically or horizontally, and this modifies the translation matrix.

    The modification we made to the original gizmo as described in Alex’s original article was to add a transition zone between the translation and rotation areas. This transition zone eases the change from translation to rotation, and makes the gizmo a little more forgiving.

    To show the location of the user’s touch on the gizmo, we render a “nub” representing the tip of the virtual joystick. As the user moves this nub further away from the center of the gizmo, we increase the translation speed. The translation speed is maximized when the nub reaches the transition area.

    When the user reaches the transition zone, we activate the rotation nub. As long as the user’s input is outside the pure translation area, we render two nubs. One (the red one) represents the velocity vector and is locked to the inner ring. The second nub (the yellow one) is the rotational nub.

    As the user moves the nub further out, we compute a lerp value between the inner and outer rings of the transition zone. We use this value to reduce translation speed as the user moves towards the edge of the translation zone, while simultaneously increasing the rotation scaling. As the user’s input reaches the outer edge of the transition zone, the translation effect is zeroed out, and the rotation effect is maximized.

    The larger the angle is from the vertical, or “forward” direction, the more rotation is added to the movement of the viewpoint. In our implementation there is some overlap between the translation and rotation modes. We have a transition zone where we are both translating and rotating. Eventually as the user pushes the joystick further out, the translation element drops to zero and the user is just rotating the viewpoint.

    The rotation speed is proportional to the angle from the initial direction vector. Once the user enters the transition zone, the translation nub is locked, and the angular deviation from the direction vector (angle α) is what controls rotation speed. As the user rotates through 180 degrees, the rotation direction suddenly changes, but in practice the user is rotating at a good clip by about 45 degrees, so we rarely run in to this situation in practice.

    Implementation Details

    The actual implementation is fairly simple. There is some code that manages processing the user input. Basically it takes the x,y locations from the touch and lets the gizmo code process it. The gizmo resets when users lift their fingers, but when they put their fingers down we process the input, calculating out from the center of the gizmo. As the touch point moves out past the inner circle, we lock the translation nub and start processing the rotation nub. The further from the center the translation nub is, the faster the translation. The further the rotation nub is from the inner circle, the faster the rotation. The more the deflection from the direction of the translation nub, the more the rotation will also attenuate the translation, providing a smooth transition from moving to rotating.

    These values are calculated for each touch input. When we want to draw the gizmo, we calculate a translation transformation from the translation nub and a rotation transform from the rotation nub. The code is straightforward. The translation and rotation values are used to calculate the model view matrix which is then passed to the shader and is used to drive around the 3D scene.

    Rendering the gizmo is left entirely to the pixel shader. We did this for rapid prototyping as it’s easy to render circles and gradients in the shader code. It also makes it easy to swap out different types of gizmo controls if you want to experiment with different settings. One of the initial requests was that the gizmo gets rendered where the user can see it rather than under the thumb where it gets hidden.

    The fragment shader code just renders the nub positions and then the gizmo rings using the distance from the center. The texture coordinates are scaled in the vertex shader so that they range from [-1,-1] to [1,1], which makes most of the shading fairly simple. Here’s the OpenGL ES 2.0 GLSL shader code.

    precision mediump float;
    
    varying vec2 v_UV1;
    varying vec3 v_Normal;
    // 2 nubs packed in vec4 - x,y is nub1, z,w nub2
    uniform vec4 u_NubPos;
    // gizmo params, just x used for inner ring
    uniform vec4 u_widgetParams;
    
    const vec4 innerColor = vec4(1.0, 1.0, 1.0, 0.4);
    const vec4 outerColor = vec4(0.2, 0.8, 0.8, 0.4);
    const vec4 innerRingColor = vec4(1.0, 0.0, 0.0, 0.5);
    const vec4 outsideCircleColor = vec4(0.0, 0.0, 0.0, 1.0);
    const vec4 nub0Color = vec4(1.0, 0.0, 0.0, 0.5);
    const vec4 nub1Color = vec4(0.0, 0.0, 0.0, 0.5);
    const float ringWidth = 0.05;
    
    void main() 
    {
    	float inner = u_widgetParams.x;
          // calculate position of nub centers
          // if not valid, are set to 1,1 (which causes clipping)
          vec2 nub0 = vec2(v_UV1.x-u_NubPos.x,v_UV1.y-u_NubPos.y);
          vec2 nub1 = vec2(v_UV1.x-u_NubPos.z,v_UV1.y-u_NubPos.w);
    
          // distance of current frag from nub positions
          float lenNub0 = length(nub0);
          float lenNub1 = length(nub1);
    
          // tex cords are scaled in in vertex
          // shader to range -1,-1 to 1,1, so center is 0,0
    
          // where is current frag from center?
          float len = length(v_UV1);
    
          it’s outside the square, discard it
          if ( len > 1.0 )
              {
                 discard;
              }
    
          // draw the two nubs, if we’re inside their radius 
          // nub0 gets drawn first
          else if ( lenNub0 < 0.10 )// hardcoded nub size
                {
                    gl_FragColor = nub0Color;
                    return;
                }
          else if ( lenNub1 < 0.10 )
               {
                    gl_FragColor = nub1Color;
                    return;
               }
    
         // else draw the rings
         else if( len >= inner && len <= inner+ringWidth)
            {
                gl_FragColor = innerRingColor;
            }
         else if ( len < inner )
            {
                gl_FragColor = innerColor;
            }
         else // draw a blended color
            {
                float m = 1.0-(len-inner/(inner+ringWidth));
                gl_FragColor = mix(vec4(0,0,0,1),outerColor,m);
            }
    }

    What’s Next

    The current prototype is still far from a final version you could use in a game: there’s plenty more to do. The biggest problem to resolve is how to make those distinctive changes in direction more fluid so gamers can quickly switch from sidestepping left to sidestepping right, which is used a lot in the type of games this is aimed at. We’ve tried to provide a framework where we can prototype different types of gizmos or fine-tune them with a minimum of effort. Some people have no trouble adapting to the controls and get comfortable with them quickly. Others feel we’ve mashed them together in an odd and unnatural way. Such is pioneering new UI concepts.

    The next step is to design a game around this proof of concept to ensure that its limitations, such as the lack of being able to look up and down, aren’t noticed or missed. This could be where you come in. We’ve done experimentation and found that it’s reasonably easy to try out different implementations and fine-tune them to get a very workable UI concept implementation, albeit one that does present a novel user input technique. But that’s also when the fun starts. So try to come up with a new joystick implementation. Perhaps you can improve on what we’ve been building here. Let us know how it works for you!

    About the Authors:
    Alex Moore has been designing video games since 1999, and has credits on 14 published games. Of those, 4 as Lead Designer, including the 2+ Million selling Aliens Vs Predator. As a freelance designer he has worked on multiple titles - in addition to personal projects on mobile devices he has most recently worked on launch titles for both Xbox One (Xbox Fitness) and PlayStation 4 (The Playroom).

    Ron Fosner has been programming graphics professionally since 1995, and is a Game and Graphics Performance engineer at Intel, specializing on mobile platforms. He’s an expert in graphics and multithreading, and has been helping game companies optimize their games on Intel architecture since 2008. He’s currently working on creating compelling OpenGL and OpenGL-ES content and pushing the boundaries of what’s possible on mobile graphics platforms.

    References:
    A new type of Touch Screen Joystick, Moore, Alex. AltDevBlogADay.

    An update to Single Joystick, Moore, Alex. AltDevBlogADay.

    A new type of Touch Screen Joystick, Moore, Alex.

    Intel and the Intel logo are trademarks of Intel Corporation in the U.S. and/or other countries.
    Copyright © 2013 Intel Corporation. All rights reserved.
    *Other names and brands may be claimed as the property of others.

  • Desenvolvedores
  • Android*
  • Android*
  • OpenGL*
  • Interfaces de toque
  • Telefone
  • Tablet
  • URL
  • Sample Code: Random Number Application

    $
    0
    0

    Download as PDF

    Download sample code

    Christopher Bird, Software Applications Engineer

    Application Origination:
    Intel SSG

    Introduction

    A Random Number Generator (RNG) is a utility or device of some type that produces a sequence of numbers on an interval such that values appear unpredictable. An RNG is an indispensable component of information security applications. In fact, a cryptographic protocol may have considerable robustness but suffer from widespread attack due to weak key generation methods underlying it. The hardware-assisted RNG can be used to fix this weakness, thus significantly increasing cryptographic robustness.

    This paper provides an overview of random number APIs and also shows how to use different APIs to generate random numbers on the Android* OS.

    We recommend that you try out the features and compile the code as you read through the paper.

    Code and Explanations

    There are four different ways to generate random numbers in Android.

    • java.util.random
    • java.security.SecureRandom
    • /dev/urandom
    • OpenSSL* API

    However, if you are using an RNG to generate a cryptographic key for protecting your data, the typical Random class is known to be easier to crack and should not be used. The other three approaches should provide strong keys.

    java.util.random

    Using Java* Random Number API is very straightforward. A call to Random.nextInt() will return a 4-byte random value ( with 2^32 possible values). This API works well for cases where you don’t rely on truly random numbers.

    for (int i = 0; i < lastVal; i += 2) {
    	dataRandomPoints[i] = (rand.nextInt() % widget_width);
    	dataRandomPoints[i+1] = (rand.nextInt() % widget_height);
    
    }
    
    

    java.security.SecureRandom

    SecureRandom resembles java.util.Random in that you can make a SecureRandom.nextInt() call to return a 4-byte random value. SecureRandom is cryptographically strong, although developers should be aware of recent recommendations that they seed SecureRandom with bytes from /dev/urandom before generating random numbers. The example below does not seed from /dev/urandom.

    SecureRandom srand = new SecureRandom();
    shouldDraw = (srand.nextInt() % randomMod );
    
    

    /dev/urandom

    Linux* operating systems (Android included) have a special file created by the kernel that can feed random numbers to applications. The slowest of the 4 implementations, it generates cryptographically safe high-entropy values by incorporating noise from parts of the operating system (e.g., device drivers) into the RNG. We can get the random number directly from the kernel level by reading from the /dev/urandom file.   /dev/urandom will access the hardware-assisted RNG if it is available.

    unsigned int cKeyBuffer[keysize];
    memset(cKeyBuffer, 0, sizeof(unsigned int) * keysize);
    
    FILE *fin;
    strcpy(filein, "/dev/urandom");
    fin = fopen(filein, "rb");
    
    if (fin != NULL) {
    	fread(cKeyBuffer, sizeof(int), keysize, fin);
    	fclose (fin);
    }
    
    

    OpenSSL API

    We also can use OpenSSL API to get random numbers in native (C) code. You can see that OpenSSL can be seeded with bytes from /dev/urandom and then can be used to generate cryptographically secure random numbers. OpenSSL API will access the hardware-assisted RNG if it is available.

    int seedbytes = 1024;
    unsigned int cKeyBuffer[keysize];
    memset(cKeyBuffer, 0, sizeof(unsigned int) * keysize);
    
    if (!opensslIsSeeded) {
    
    	if (!RAND_load_file("/dev/urandom", seedbytes)) {
    		__android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to seed OpenSSL RNG");
    		return jKeyBuffer;
    	}
    
    	opensslIsSeeded = 1;
    }
    
    if (!RAND_bytes((unsigned char *)cKeyBuffer, keysize * sizeof(int))) {
    	__android_log_print(ANDROID_LOG_ERROR, TAG, "Faled to create OpenSSSL random integers: %ul", ERR_get_error);
    }
    
    

    Conclusion

    By implementing code like the samples described in this paper, you can quickly learn how to use four different ways to generate random numbers.

    About the author

    Christopher Bird is a member of the Intel Software and Solutions Group (SSG), Developer Relations Division, Intel® Atom™ Processor High Touch Software Enabling team.

     

    Notices

    INFORMATION IN THIS DOCUMENT IS PROVIDED IN CONNECTION WITH INTEL PRODUCTS. NO LICENSE, EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE, TO ANY INTELLECTUAL PROPERTY RIGHTS IS GRANTED BY THIS DOCUMENT. EXCEPT AS PROVIDED IN INTEL'S TERMS AND CONDITIONS OF SALE FOR SUCH PRODUCTS, INTEL ASSUMES NO LIABILITY WHATSOEVER AND INTEL DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY, RELATING TO SALE AND/OR USE OF INTEL PRODUCTS INCLUDING LIABILITY OR WARRANTIES RELATING TO FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR INFRINGEMENT OF ANY PATENT, COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT.

    UNLESS OTHERWISE AGREED IN WRITING BY INTEL, THE INTEL PRODUCTS ARE NOT DESIGNED NOR INTENDED FOR ANY APPLICATION IN WHICH THE FAILURE OF THE INTEL PRODUCT COULD CREATE A SITUATION WHERE PERSONAL INJURY OR DEATH MAY OCCUR.

    Intel may make changes to specifications and product descriptions at any time, without notice. Designers must not rely on the absence or characteristics of any features or instructions marked "reserved" or "undefined." Intel reserves these for future definition and shall have no responsibility whatsoever for conflicts or incompatibilities arising from future changes to them. The information here is subject to change without notice. Do not finalize a design with this information.

    The products described in this document may contain design defects or errors known as errata which may cause the product to deviate from published specifications. Current characterized errata are available on request.

    Contact your local Intel sales office or your distributor to obtain the latest specifications and before placing your product order.

    Copies of documents which have an order number and are referenced in this document, or other Intel literature, may be obtained by calling 1-800-548-4725, or go to: http://www.intel.com/design/literature.htm

    Software and workloads used in performance tests may have been optimized for performance only on Intel microprocessors. Performance tests, such as SYSmark* and MobileMark*, are measured using specific computer systems, components, software, operations, and functions. Any change to any of those factors may cause the results to vary. You should consult other information and performance tests to assist you in fully evaluating your contemplated purchases, including the performance of that product when combined with other products.

    Any software source code reprinted in this document is furnished under a software license and may only be used or copied in accordance with the terms of that license.

    Intel, the Intel logo, and Atom  are trademarks of Intel Corporation in the US and/or other countries.

    Copyright © 2014 Intel Corporation. All rights reserved.

    *Other names and brands may be claimed as the property of others.

     

  • Desenvolvedores
  • Android*
  • Android*
  • URL
  • Intel Learning Series para desarrolladores para Android*, n.º 4: Sensores de tabletas Android

    $
    0
    0

    1. Sensores en tabletas Android con procesador Intel® Atom™

    Las tabletas basadas en procesadores Intel Atom admiten una amplia variedad de sensores de hardware. Estos sensores se usan para detectar el movimiento y los cambios de posición, e informar los parámetros de entorno del ambiente. El diagrama de bloques de la Figura 1 muestra una posible configuración de sensores en una tableta Android basada en procesador Intel Atom típica.

    Sobre la base de los datos que informan, podemos clasificar los sensores en las clases y tipos que se muestran más abajo, en la Tabla 4.1.

    Tabla 4.1    Tipos de sensores que admite la plataforma Android

    Sensores de posición
    Sensores de posición
    Acelerómetro (TYPE_ACCELEROMETER)Mide las aceleraciones del dispositivo en m/s2Detección de movimiento
    Giroscopio (TYPE_GYROSCOPE)Mide la velocidad de rotación del dispositivoDetección de rotación
    Magnetómetro (TYPE_MAGNETIC_FIELD)Mide la intensidad del campo geomagnético de la Tierra en µTBrújula
    Proximidad (TYPE_PROXIMITY)Mide la proximidad de los objetos en cmDetección de objeto cercano
    GPS (no es un tipo de sensor de android.hardware)Determina la ubicación geográfica precisa del dispositivoDetección precisa de ubicación geográfica
    Sensores de entornoSensor de luz ambiente (TYPE_LIGHT)Mide el nivel de luz ambiente en lxControl automático de brillo de la pantalla

    Marco de trabajo de sensores en Android

    El marco de trabajo de sensores en Android proporciona mecanismos que permiten acceder a los sensores y sus datos, con la excepción del GPS, al que se accede mediante los servicios de localización de Android. Esto lo analizaremos más adelante en este mismo capítulo. El marco de trabajo de sensores forma parte del paquete android.hardware. En la Tabla 4.2 se incluye una lista de las clases e interfaces principales en las que consiste el marco de trabajo de sensores.

    Tabla 4.2    Marco de trabajo de sensores en la plataforma Android

    NombreTipoDescripción
    SensorManagerClaseSe usa para crear una instancia del servicio de sensor. Proporciona diferentes métodos para acceder a los sensores, registrar y cancelar el registro de procesos de escucha (listeners) de eventos de sensor, etc.
    SensorClaseSe usa para crear una instancia de un sensor específico.
    SensorEventClaseEl sistema la usa para publicar datos de sensores. Incluye los valores de datos de sensor sin procesar, la precisión de los datos y una marca de tiempo.
    SensorEventListenerInterfazProporciona métodos de devolución de llamada (callback) para recibir notificaciones de SensorManager cuando han cambiado los datos del sensor o la precisión del sensor.

    2.1 Cómo obtener la configuración del sensor

    Es decisión exclusiva del fabricante qué sensores estarán disponibles en el dispositivo. Es posible usar el marco de trabajo de sensores para descubrir cuáles son los sensores disponibles en el tiempo de ejecución; pare eso se debe invocar el método getSensorList() de SensorManager con el parámetro “Sensor.TYPE_ALL”. El Ejemplo de código 1 muestra en un fragmento una lista de sensores disponibles y el vendedor, la potencia y la precisión de la información de cada sensor.

    package com.intel.deviceinfo;      
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map; 	 
    import android.app.Fragment;
    import android.content.Context;
    import android.hardware.Sensor;
    import android.hardware.SensorManager;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ListView;
    import android.widget.SimpleAdapter; 
    	 
    public class SensorInfoFragment extends Fragment {  
        private View mContentView;  
        private ListView mSensorInfoList;     
        SimpleAdapter mSensorInfoListAdapter;
        private List<Sensor> mSensorList; 
     
        private SensorManager mSensorManager;  
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
        }
        @Override
        public void onPause() 
        { 
            super.onPause();
        }
        @Override
        public void onResume() 
        {
            super.onResume();
        }
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            mContentView = inflater.inflate(R.layout.content_sensorinfo_main, null);
            mContentView.setDrawingCacheEnabled(false);
            mSensorManager = (SensorManager)getActivity().getSystemService(Context.SENSOR_SERVICE);
            mSensorInfoList = (ListView)mContentView.findViewById(R.id.listSensorInfo);
            mSensorInfoList.setOnItemClickListener( new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> arg0, View view, int index, long arg3) {
                    // with the index, figure out what sensor was pressed
                    Sensor sensor = mSensorList.get(index);
                    // pass the sensor to the dialog.
                    SensorDialog dialog = new SensorDialog(getActivity(), sensor);
                    dialog.setContentView(R.layout.sensor_display);
                    dialog.setTitle("Sensor Data");
                    dialog.show();
                }
            });            
            return mContentView;
        }      
        void updateContent(int category, int position) {
            mSensorInfoListAdapter = new SimpleAdapter(getActivity(), 
              getData() , android.R.layout.simple_list_item_2,
              new String[] {
                  "NAME",
                  "VALUE"
              },
              new int[] { android.R.id.text1, android.R.id.text2 });
          mSensorInfoList.setAdapter(mSensorInfoListAdapter);
        }
        protected void addItem(List<Map<String, String>> data, String name, String value)   {
            Map<String, String> temp = new HashMap<String, String>();
            temp.put("NAME", name);
            temp.put("VALUE", value);
            data.add(temp);
        }  
        private List<? extends Map<String, ?>> getData() {
            List<Map<String, String>> myData = new ArrayList<Map<String, String>>();
            mSensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL);
            for (Sensor sensor : mSensorList ) {
                addItem(myData, sensor.getName(),  "Vendor: " + sensor.getVendor() + ", min. delay: " + sensor.getMinDelay() +", power while in use: " + sensor.getPower() + "mA, maximum range: " + sensor.getMaximumRange() + ", resolution: " + sensor.getResolution());
            }
            return myData;
        }
    }

    Ejemplo de código 1: Fragmento que muestra la lista de sensores**. Fuente: Intel Corporation, 2012

    2.2 Sistema de coordenadas de sensores

     

    El marco de trabajo de sensores comunica datos de sensores mediante el uso de un sistema de coordenadas estándar de 3 ejes, en el cual X, Y y Z están representadas por values[0], values[1] y values[2], respectivamente, en el objeto SensorEvent.

    0 0 1 95 544 intel 4 1 638 14.0

    Sensores tales como el de luz, el de temperatura y el de proximidad devuelven un solo valor. Para estos sensores sólo se usa values[0] en el objeto SensorEvent.

    Otros sensores comunican datos en el sistema de coordenadas estándar de 3 ejes. La siguiente es una lista de esos sensores:

    • Acelerómetro
    • Sensor de gravedad
    • Giroscopio
    • Sensor de campo geomagnético

    El sistema de coordenadas de sensores de 3 ejes se define con relación a la pantalla del dispositivo en su orientación natural (predeterminada). En el caso de las tabletas, la orientación natural es por lo general la horizontal, mientras que para los teléfonos es la vertical. Cuando se sostiene un dispositivo en su orientación natural, el eje x es horizontal y apunta a la derecha, el eje y es vertical y apunta hacia arriba y el eje z apunta hacia fuera de la pantalla. La Figura 4.2 muestra el sistema de coordenadas de sensores para una tableta.


    Figura 4.2. Sistema de coordenadas de sensores
    Fuente: Intel Corporation, 2012

    La cuestión más importante que se debe tener en cuenta es que el sistema de coordenadas del sensor nunca cambia cuando el dispositivo se mueve o se modifica su orientación.

    2.3 Eventos de sensor de monitorización

    El marco de trabajo de sensores informa datos a los objetos SensorEvent. Para monitorizar los datos de un sensor específico, una clase puede implementar la interfaz SensorEventListener y registrarse en el SensorManager del sensor. El marco de trabajo informa a la clase acerca de los cambios de estado del sensor por medio de los siguientes dos métodos de devolución de llamada de SensorEventListener implementados por la clase:

    onAccuracyChanged()
    y
    onSensorChanged()

    En el Ejemplo de código 2 se implementa el SensorDialog utilizado en el ejemplo de SensorInfoFragment que vimos en la sección “Cómo obtener la configuración del sensor”.

    package com.intel.deviceinfo;
      
    import android.app.Dialog;
    import android.content.Context;
    import android.hardware.Sensor;
    import android.hardware.SensorEvent;
    import android.hardware.SensorEventListener;
    import android.hardware.SensorManager;
    import android.os.Bundle;
    import android.widget.TextView;
      
    public class SensorDialog extends Dialog implements SensorEventListener {
        Sensor mSensor;
        TextView mDataTxt;
        private SensorManager mSensorManager; 
           
      
        public SensorDialog(Context ctx, Sensor sensor) {
            this(ctx);
            mSensor = sensor;
        }
           
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mDataTxt = (TextView) findViewById(R.id.sensorDataTxt);
            mDataTxt.setText("...");
            setTitle(mSensor.getName());
        }
           
        @Override
        protected void onStart() {
            super.onStart();
            mSensorManager.registerListener(this, mSensor,  SensorManager.SENSOR_DELAY_FASTEST);
        }
                 
        @Override
        protected void onStop() {
            super.onStop();
            mSensorManager.unregisterListener(this, mSensor);
        }
      
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
      
        @Override
        public void onSensorChanged(SensorEvent event) {
            if (event.sensor.getType() != mSensor.getType()) {
                return;
            }
            StringBuilder dataStrBuilder = new StringBuilder();
            if ((event.sensor.getType() == Sensor.TYPE_LIGHT)||
                (event.sensor.getType() == Sensor.TYPE_TEMPERATURE)) {
                dataStrBuilder.append(String.format("Data: %.3fn", event.values[0]));
            }
            else{         
                dataStrBuilder.append( 
                    String.format("Data: %.3f, %.3f, %.3fn", 
                    event.values[0], event.values[1], event.values[2] ));
            }
            mDataTxt.setText(dataStrBuilder.toString());
        }
    }

    Ejemplo de código 2: Diálogo que muestra los valores del sensor**

    2.4 Sensores de movimiento

    Los sensores de movimiento se usan para monitorizar el movimiento del dispositivo, ya sea agitación, giro, balanceo o inclinación. El acelerómetro y el giroscopio son dos sensores de movimiento de los cuales disponen muchas tabletas y teléfonos.

    Los sensores de movimiento comunican datos en el sistema de coordenadas de sensores, en el cual los tres valores del objeto SensorEvent, values[0], values[1] y values[2], representan valores para los ejes x, y y z, respectivamente.

    Para entender los sensores de movimiento y aplicar los datos en una aplicación, necesitamos usar algunas fórmulas físicas relacionadas con la fuerza, la masa, la aceleración, las leyes del movimiento de Newton y la relación entre varias de estas entidades a lo largo del tiempo. Aquel que desee conocer más acerca de estas fórmulas y relaciones puede consultar libros de texto de física o materiales de dominio público.

    El acelerómetro mide la aceleración que se aplica al dispositivo.

    Tabla 4.3    El acelerómetro        Fuente: Intel Corporation, 2012

    SensorTipoDatos de SensorEvent (m/s2)Descripción
    AcelerómetroTYPE_ACCELEROMETERvalues[0]Aceleración en el eje x
    values[1]Aceleración en el eje y
    values[2]Aceleración en el eje z

    El concepto del acelerómetro se deriva de la segunda ley del movimiento de Newton:
    a = F/m

    La aceleración de un objeto es el resultado de la fuerza neta que se aplica al objeto. Entre las fuerzas externas se incluye la que se aplica a todos los objetos de la Tierra: la gravedad. Es directamente proporcional a la fuerza neta F que se aplica al objeto e inversamente proporcional a la masa m del objeto.

    En nuestro código, en lugar de usar en forma directa la ecuación de arriba, por lo general nos interesa el resultado que produce la aceleración en la velocidad y la posición del dispositivo durante un período de tiempo. La siguiente ecuación describe la relación entre la velocidad v1 de un objeto, su velocidad original v0, la aceleración a y el tiempo t:
    v1 = v0 + at

    Para calcular el desplazamiento s del objeto, usamos la ecuación siguiente:
    s = v0t + (1/2)at2

    En muchos casos, comenzamos con la condición v0 igual a 0 (antes de que el dispositivo comience a moverse), lo que simplifica la ecuación. Así queda:
    s = at2/2

    Debido a la gravedad, la aceleración gravitacional, que se representa con el símbolo g, se aplica a todo objeto que se encuentre en la Tierra. Esta magnitud es independiente de la masa del objeto. Sólo depende de la altura del objeto respecto del nivel del mar. Su valor varía entre 9,78 y 9,82 (m/s2). Adoptamos el valor estándar convencional de g:
    g = 9,80665 (m/s2)

    Como el acelerómetro devuelve los valores según un sistema de coordenadas multidimensional, en nuestro código podemos calcular las distancias a lo largo de los ejes x, y y z con las siguientes ecuaciones.

    Sx = AxT2/2

    Sy=AyT2/2

    Sz=AzT2/2

    Donde Sx, Sy y Sz son los desplazamientos sobre el eje x, el eje y y el eje z, respectivamente, y Ax, Ay y Az son las aceleraciones sobre los ejes x, y y z, respectivamente. T es el tiempo del período medido.

    En el Ejemplo de código 3 se muestra cómo crear una instancia de acelerómetro.

    public class SensorDialog extends Dialog implements SensorEventListener {
        ... 
        private Sensor mSensor;
        private SensorManager mSensorManager; 
           
        public SensorDialog(Context context) {
            super(context);
            mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
            mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        ...
    }

    Ejemplo de código 3: Creación de una instancia de acelerómetro (**)
    Fuente: Intel Corporation, 2012

    A veces no usamos los valores de las tres dimensiones. También puede ocurrir que necesitemos tomar en cuenta la orientación del dispositivo. Por ejemplo, cuando desarrollamos una aplicación para un laberinto, sólo usamos la aceleración gravitacional en los ejes x e y para calcular las distancias y las direcciones de movimiento de la bola a partir de la orientación del dispositivo. El siguiente fragmento de código (Ejemplo de código 4) describe la lógica.

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER) {
            return;
        } 
    float accelX, accelY;
    ...
    //detect the current rotation currentRotation from its “natural orientation”
    //using the WindowManager
        switch (currentRotation) {
            case Surface.ROTATION_0:
                accelX = event.values[0];
                accelY = event.values[1];
                break;
            case Surface.ROTATION_90:
                accelX = -event.values[0];
                accelY = event.values[1];
                break;
            case Surface.ROTATION_180:
                accelX = -event.values[0];
                accelY = -event.values[1];
                break;
            case Surface.ROTATION_270:
                accelX = event.values[0];
                accelY = -event.values[1];
                break;
        }
        //calculate the ball’s moving distances along x, and y using accelX, accelY and the time delta
            ...
        }
    }

    Ejemplo de código 4: Consideración de la orientación del dispositivo cuando se usan datos del acelerómetro en un juego de laberinto**
    Fuente: Intel Corporation, 2012

    El giroscopio mide la velocidad de rotación del dispositivo alrededor de los ejes x, y y z, como se muestra en la Tabla 4.4. Los valores de datos del giroscopio pueden ser positivos o negativos. Si se mira el origen desde una posición en el semieje positivo y si la rotación alrededor del eje es en sentido contrario al de las agujas del reloj, el valor es positivo; si la rotación es en el sentido de las agujas del reloj, el valor es negativo. También podemos determinar el sentido de los valores del giroscopio con la “regla de la mano derecha”, que se ilustra en la Figura 4.3.


     

     

     

     

     

     

     

    Tabla 4.4.    El giroscopio        Fuente: Intel Corporation, 2012

    SensorTipoDatos de SensorEvent (rad/s)Descripción
    GiroscopioTYPE_GYROSCOPEvalues[0]Velocidad de rotación alrededor del eje x
    values[1]Velocidad de rotación alrededor del eje y
    values[2]Velocidad de rotación alrededor del eje z

    En el Ejemplo de código 5 se muestra cómo crear una instancia de giroscopio.

    public class SensorDialog extends Dialog implements SensorEventListener {
        ... 
        private Sensor mGyro;
        private SensorManager mSensorManager; 
           
        public SensorDialog(Context context) {
            super(context);
            mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
            mGyro = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
        ...
    }

    Ejemplo de código 5: Creación de una instancia de giroscopio**
    Fuente: Intel Corporation, 2012

    2.5 Sensores de posición

    Muchas tabletas Android admiten dos sensores de posición: el magnetómetro y el sensor de proximidad. El magnetómetro mide las intensidades del campo magnético terrestre a lo largo de los ejes x, y y z, mientras que el sensor de proximidad detecta la distancia del dispositivo a otro objeto.

    2.5.1 Magnetómetro

    El uso más importante que da el sistema Android al magnetómetro (que se describe en la Tabla 4.5) es la implementación de la brújula.

    Tabla 4.5    El magnetómetro        Fuente: Intel Corporation, 2012

    SensorTipoDatos de SensorEvent (µT)Descripción
    MagnetómetroTYPE_MAGNETIC_FIELDvalues[0]Intensidad del campo magnético terrestre a lo largo del eje x
    values[1]Intensidad del campo magnético terrestre a lo largo del eje y
    values[2]Intensidad del campo magnético terrestre a lo largo del eje z

    En el Ejemplo de código 6 se muestra cómo crear una instancia de magnetómetro.

    public class SensorDialog extends Dialog implements SensorEventListener {
        ... 
        private Sensor mMagnetometer;
        private SensorManager mSensorManager; 
           
        public SensorDialog(Context context) {
            super(context);
            mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
            mMagnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        ...
    }

    Ejemplo de código 6: Creación de una instancia de magnetómetro**
    Fuente: Intel Corporation, 2012

    2.5.2 Proximidad

    El sensor de proximidad proporciona la distancia entre el dispositivo y otro objeto. El dispositivo lo puede usar para detectar si está siendo sostenido cerca del usuario (ver Tabla 4.6) y así determinar si el usuario está haciendo o recibiendo llamadas telefónicas.

    Tabla 4.6    El sensor de proximidad        Fuente: Intel Corporation, 2012

    SensorTipoDatos de SensorEventDescripción
    ProximidadTYPE_PROXIMITYvalues[0]Distancia en cm respecto de un objeto. Algunos sensores de proximidad sólo informan un valor booleano para indicar si el objeto está suficientemente cerca.

    En el Ejemplo de código 7 se muestra cómo crear una instancia de sensor de proximidad.

    public class SensorDialog extends Dialog implements SensorEventListener {
        ... 
        private Sensor mProximity;
        private SensorManager mSensorManager; 
           
        public SensorDialog(Context context) {
            super(context);
            mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
            mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
        ...
    }

    Ejemplo de código 7: Creación de una instancia de sensor de proximidad**
    Fuente: Intel Corporation, 2012

    2.6 Sensores de entorno

    Los sensores de entorno detectan e informan los parámetros de entorno del ambiente en el que se encuentra el dispositivo. La disponibilidad de cada sensor en particular depende sólo del fabricante del dispositivo. El sensor de luz ambiente (ALS) está disponible en muchas tabletas Android.

    2.6.1 Sensor de luz ambiente (ALS)

    El sistema usa el sensor de luz ambiente, que se describe en la Tabla 4.7, para detectar la iluminación del entorno y ajustar automáticamente el brillo de la pantalla según lo detectado.

    Tabla 4.7    El sensor de luz ambiente        Fuente: Intel Corporation, 2012

    SensorTipoDatos de SensorEvent (lx)Descripción
    Sensor de luz ambienteTYPE_LIGHTvalues[0]Iluminación cerca del dispositivo

    En el Ejemplo de código 8 se muestra cómo crear una instancia del sensor de luz ambiente.

        ... 
        private Sensor mALS;
        private SensorManager mSensorManager; 
      
        ... 
            mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
            mALS = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        ...

    Ejemplo de código 8: Creación de una instancia de sensor de luz ambiente**
    Fuente: Intel Corporation, 2012

    2.7 Pautas de optimización y rendimiento de sensores

    Para usar sensores en sus aplicaciones, es aconsejable que siga las siguientes pautas:

    • Antes de usar un sensor específico, siempre compruebe que esté disponible
      La plataforma Android no exige la inclusión o exclusión de sensores específicos en el dispositivo. Los sensores que se incluyen es algo que decide el fabricante del dispositivo en forma exclusiva. Antes de usar un sensor en su aplicación, siempre compruebe primero que esté disponible.
    • Siempre cancele el registro de los procesos de escucha del sensor
      Si la actividad que implementa el proceso de escucha del sensor se vuelve invisible, o si el diálogo se detiene, cancele el registro del proceso de escucha del sensor. Se puede hacer con el método onPause() de la actividad o el método onStop() del diálogo. Si no cumple con esta pauta, el sensor continuará adquiriendo datos y, como consecuencia, agotará la batería.
    • No bloquee el método onSensorChanged()
      El sistema llama con frecuencia al método onSensorChanged() para informar datos de sensor. Debe haber la menor cantidad de lógica posible dentro de este método. Los cálculos complicados con datos del sensor se deben mover hacia fuera de este método.
    • Siempre pruebe en dispositivos reales las aplicaciones que usen sensores
      Todos los sensores que se describen en esta sección son de tipo hardware. Es posible que el emulador de Android no sea suficiente para simular las funciones y el rendimiento de los sensores.

    3 GPS y ubicación

    El Sistema de Posicionamiento Global (Global Positioning System, GPS) es un sistema satelital que proporciona información precisa de ubicación geográfica en todo el mundo. Está disponible en una gran variedad de tabletas Android. En muchos aspectos, se comporta como un sensor de posición. Puede proporcionar datos precisos de ubicación para las aplicaciones que se ejecutan en el dispositivo. En la plataforma Android, el marco de trabajo de sensores no maneja el GPS de manera directa. Lo que ocurre, en cambio, es que el servicio de localización Android accede a los datos del GPS y los transfiere a las aplicaciones a través de las devoluciones de llamada de los procesos de escucha de ubicación.

    3.1 Servicios de localización de Android

    Usar el GPS no es la única manera de obtener la información de ubicación en los dispositivos Android. El sistema también puede utilizar Wi-Fi*, redes celulares y otras redes inalámbricas para hacerse con la ubicación actual del dispositivo. El GPS y las redes inalámbricas (incluidas las Wi-Fi y las celulares) actúan como “proveedores de ubicación” para los servicios de localización de Android. En la Tabla 4.8 se incluye una lista de las clases e interfaces principales que se usan para acceder a los servicios de localización de Android:

    Tabla 4.8    El servicio de localización de la plataforma Android        Fuente: Intel Corporation, 2012

    NombreTipoDescripción
    LocationManagerClaseSe usa para acceder a los servicios de localización. Proporciona diversos métodos para solicitar actualizaciones periódicas de ubicación para una aplicación, o para enviar alertas de proximidad.
    LocationProviderClase abstractaEs la supercalse abstracta para proveedores de ubicación.
    LocationClaseLos proveedores de ubicación la utilizan para encapsular datos geográficos.
    LocationListenerInterfazSe usa para recibir notificaciones de LocationManager.

    3.2 Cómo obtener actualizaciones de ubicación por GPS

     

    De manera similar al mecanismo de usar el marco de trabajo de sensores para acceder a datos de sensores, la aplicación implementa varios métodos de devolución de llamada definidos en la interfaz LocationListener para recibir actualizaciones de ubicación por GPS. LocationManager envía notificaciones de actualización de GPS a la aplicación por medio de estas devoluciones de llamada (la regla “No nos llame, nosotros lo llamaremos”).

    Para acceder a los datos de ubicación GPS de la aplicación, es necesario que solicite el permiso de acceso a ubicación precisa en su archivo de manifiesto de Android (Ejemplo de código 9).

    <manifest ...>
    ...
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"...  
    </manifest>

    Ejemplo de código 9: Cómo solicitar el permiso de acceso a ubicación precisa en el archivo de manifiesto**
    Fuente: Intel Corporation, 2012

    En el Ejemplo de código 10 se muestra cómo obtener actualizaciones del GPS y mostrar las coordenadas de latitud y longitud en una vista de texto de diálogo.

    package com.intel.deviceinfo;
      
    import android.app.Dialog;
    import android.content.Context;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.widget.TextView;
      
    public class GpsDialog extends Dialog implements LocationListener {
        TextView mDataTxt;
        private LocationManager mLocationManager;
           
        public GpsDialog(Context context) {
            super(context);
            mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
        }
      
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
                 mDataTxt = (TextView) findViewById(R.id.sensorDataTxt);
              mDataTxt.setText("...");
                 
            setTitle("Gps Data");
        }
           
        @Override
        protected void onStart() {
            super.onStart();
            mLocationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 0, 0, this);
        }
                 
        @Override
        protected void onStop() {
            super.onStop();
            mLocationManager.removeUpdates(this);
        }
      
        @Override
        public void onStatusChanged(String provider, int status, 
            Bundle extras) {
        }
      
        @Override
        public void onProviderEnabled(String provider) {
        }
      
        @Override
        public void onProviderDisabled(String provider) {
        }
      
        @Override
        public void onLocationChanged(Location location) {
            StringBuilder dataStrBuilder = new StringBuilder();
            dataStrBuilder.append(String.format("Latitude: %.3f,   Logitude%.3fn", location.getLatitude(), location.getLongitude()));
            mDataTxt.setText(dataStrBuilder.toString());
                 
        }
    }

    Ejemplo de código 10: Diálogo que muestra los datos de ubicación del GPS**
    Fuente: Intel Corporation, 2012

    3.3 Pautas de optimización y rendimiento del GPS y la localización

    El GPS proporciona la información de ubicación más exacta del dispositivo. Sin embargo, al ser una prestación de hardware, consume energía adicional. Por otra parte, al GPS le lleva tiempo obtener sus primeros datos de ubicación. Las siguientes son algunas pautas que se deben seguir al desarrollar aplicaciones que utilicen el GPS y datos de ubicación:

    • Considere todos los proveedores posibles
      Además de GPS_PROVIDER, está NETWORK_PROVIDER. Si sus aplicaciones sólo necesitan los datos de ubicación aproximada, puede considerar el uso de NETWORK_PROVIDER.
    • Use las ubicaciones guardadas en el caché
      Al GPS le lleva tiempo obtener sus primeros datos de ubicación. Cuando la aplicación está esperando que el GPS obtenga una actualización de ubicación precisa, puede usar primero las ubicaciones que proporciona el método LocationManager’s getlastKnownLocation() para realizar parte del trabajo.
    • Reduzca al mínimo la frecuencia y la duración de las solicitudes de actualización de ubicación
      Debe solicitar la solicitud de ubicación sólo cuando sea necesario y cancelar el registro del administrador de ubicación cuando ya no necesite las actualizaciones.

    4. Resumen

    La plataforma Android proporciona interfaces de programación de aplicaciones (API) para que los desarrolladores accedan a los sensores integrados de los dispositivos. Estos sensores son capaces de proporcionar datos sin procesar acerca del movimiento, la posición y las condiciones de entorno del ambiente actuales del dispositivo con gran precisión. Al desarrollar aplicaciones que usen sensores, debe seguir los procedimientos recomendados para mejorar el rendimiento y aumentar la eficiencia.


    Aviso de optimización

    Los compiladores de Intel pueden o no optimizar al mismo grado para microprocesadores que no sean de Intel en el caso de optimizaciones que no sean específicas para los microprocesadores de Intel. Entre estas optimizaciones se encuentran las de los conjuntos de instrucciones SSE2, SSE3 y SSE3, y otras. Intel no garantiza la disponibilidad, la funcionalidad ni la eficacia de ninguna optimización en microprocesadores no fabricados por Intel.

    Las optimizaciones de este producto que dependen de microprocesadores se crearon para utilizarlas con microprocesadores de Intel. Ciertas optimizaciones no específicas para la microarquitectura de Intel se reservan para los microprocesadores de Intel. Consulte las guías para el usuario y de referencia correspondientes si desea obtener más información relacionada con los conjuntos de instrucciones específicos cubiertos por este aviso.

  • Intel for Android Developers Learning Series
  • Desenvolvedores
  • Parceiros
  • Professores
  • Estudantes
  • Android*
  • Android*
  • Avançado
  • Principiante
  • Intermediário
  • Sensores
  • Telefone
  • Tablet
  • URL
  • Intel Learning Series para desarrolladores para Android*, n.º 5: Cómo instalar el SDK de Android* para la arquitectura Intel®

    $
    0
    0

    1. Sistemas operativos compatibles

    Se admiten los siguientes sistemas operativos:

    • Windows XP* (32 bits), Vista* (32 o 64 bits) o Windows 7* (32 o 64 bits)
    • Mac OSX* (32 o 64 bits)
    • Linux* (Ubuntu, Fedora); GNU C Library (glibc) 2.7 o superior.
    • En Linux Ubuntu, se requiere versión 8.04 o superior.
    • En Fedora, las versiones de destino son la F-12 y superiores.
    • Las distribuciones de 64 bits deben ser capaces de ejecutar aplicaciones de 32 bits.

    2. Requisitos de hardware

    El SDK de Android* requiere espacio en disco para todos los componentes que elija instalar. Se necesita espacio adicional en disco para ejecutar el emulador, por ejemplo, con el fin de crear tarjetas SD para los dispositivos virtuales de Android* (AVD).

    3. Instalación del JDK

    El SDK requiere, como mínimo, Java* JDK 5 o JDK 6. También admite JDK 7. No es suficiente con el JRE (Java Runtime Environment) solamente. Si su sistema no tiene instalado JDK 5, 6 o 7, puede descargar JDK SE 7 de http://www.oracle.com/technetwork/java/javase/downloads/index.html e instalarlo en su equipo.

    4. Instalación de Eclipse*

    Se recomienda firmemente instalar el SDK con Eclipse* para desarrollar aplicaciones Android. Vaya a http://www.eclipse.org/downloads/ para descargar o actualizar Eclipse. Sugerimos usar las siguientes configuraciones de Eclipse si se desea desarrollar aplicaciones Android para la arquitectura Intel:

    • Eclipse 3.5 (Galileo) o superior
    • Eclipse Classic (versiones 3.5.1 y superiores)
    • Android Development Tools Plugin (recomendado)

    5. Instalación de Apache Ant (opcional)

    Se recomienda firmemente usar un entorno de desarrollo integrado, como Eclipse, para desarrollar aplicaciones Android. Pero, como alternativa, se puede usar Apache Ant para trabajar con el SDK a fin de crear aplicaciones Android. Visite http://ant.apache.org/ para descargar las distribuciones binarias e instalar Ant. Si se quiere trabajar con el SDK, se necesita Ant 1.8 o superior.

    6. Descarga del SDK Starter Package y cómo agregar los componentes del SDK

    El SDK Starter Package se puede descargar de la página http://developer.android.com/sdk/index.html. Este paquete no incluye los componentes específicos de la plataforma necesarios para desarrollar aplicaciones Android. Sólo proporciona las herramientas básicas del SDK. Usted debe descargar el resto de los componentes de la plataforma
    Después de instalar el SDK Starter Package, ejecute Android SDK and AVD Manager.

    • En Windows*, seleccione Inicio > Todos los programas > Android SDK Tools > SDK Manager
    • En Linux, ejecute asdk/tools/android, donde asdk representa el nombre de su directorio de Android SDK

    En el panel izquierdo del cuadro de diálogo Android* SDK and AVD Manager, seleccione Available packages; en el panel derecho, haga clic y expanda el nodo Android Repository, y seleccione los paquetes que desee instalar, como se muestra en la Figura 5.1.
    Para tener en cuenta: es posible que se muestre un mensaje de error si intenta descargar desde detrás de un firewall. Si esto ocurre, vuelva a intentarlo desde fuera del firewall.
    Si sigue viendo el mensaje de error, cierre el SDK Manager, haga clic con el botón derecho en el menú Inicio y seleccione Ejecutar como administrador. Estos dos pasos resuelven la mayoría de los mensajes de error que puedan aparecer mientras intenta realizar la descarga.

    7. Cómo configurar Eclipse para que funcione con el SDK

    Si usa el entorno de desarrollo integrado (IDE) de Eclipse* para desarrollar software, recomendamos firmemente que instale y configure el complemento Android Development Tool (ADT) Plugin.

    7.1 Instalación del ADT Plugin para Eclipse

    Los siguientes son los pasos de instalación del ADT Plugin para Eclipse:


    Figura 5.2Cuadro de diálogo Add Repository

    1. Inicie Eclipse, seleccione Help > Install New Software en el cuadro de diálogo Install, y haga clic en el botón Add.
    2. En el cuadro de diálogo Add Repository, escriba ADT Plugin en el campo Name e ingrese https://dl-ssl.google.com/android/eclipse/ en el campo Location, como se muestra en la Figura 5.2, y luego haga clic en OK.
    3. Regresará al cuadro de diálogo Install, se conectará con el servidor de repositorio de Google y mostrará los paquetes de ADT disponibles, como se muestra en la Figura 5.3.


      Figura 5.3Lista de paquetes de ADT

    4. Seleccione Next, acepte el acuerdo de licencia y seleccione Finish.
    5. Reinicie Eclipse.

    7.2 Configuración del ADT Plugin

    Para configurar el ADT Plugin, siga estos pasos:

    1. Inicie Eclipse y seleccione Windows > Preferences
    2. En el panel izquierdo del cuadro de diálogo Preferences, seleccione Android. En el panel derecho, use el botón Browse para navegar al directorio en el que instaló Android* SDK y haga clic en Apply. Aparecerá una lista de destinos del SDK que usted ha instalado. En este momento, haga clic en OK.


    Figura 5.4 Cuadro de diálogo Preferences

    Después de seguir los pasos descritos más arriba, tendrá a disposición las herramientas necesarias para iniciar el desarrollo de Android para la arquitectura Intel. Ahora tiene todo lo que necesita para escribir su primera aplicación, pero quizá sería mejor instalar también el Emulador de Arquitectura Intel® (x86) en este momento, para poder probar la aplicación ni bien esté lista. En la siguiente sección se mostrará la instalación del Emulador de Arquitectura Intel® (x86). Analizaremos la creación de una imagen de emulador con recursos AOSP y la emulación de las imágenes de sistema resultantes para x86. También se verán algunas nuevas prestaciones incluidas en Gingerbread* y Ice Cream Sandwich*.

    Información general sobre la emulación de Android Virtual Device

    Android funciona en dispositivos con diversos factores de forma y diferentes tamaños de pantalla, funcionalidades de hardware y prestaciones. Un dispositivo característico tiene muchas funcionalidades de software (API de Android) y hardware, tales como sensores, GPS, cámara, tarjeta SD y pantalla multitáctil de dimensiones específicas.

    El emulador es bastante flexible y es posible configurarlo con diferentes opciones de configuración de software y hardware. Los desarrolladores pueden configurar el emulador con la configuración denominada Dispositivo Virtual de Android (AVD). Se podría pensar en el AVD como un conjunto de archivos de configuración que especifican diferentes funcionalidades de software de Android y hardware del dispositivo. El emulador de Android usa estas configuraciones de AVD para configurar e iniciar en el emulador la imagen virtual de Android apropiada.

    Como se documenta en el sitio web de Android (http://developer.android.com/guide/developing/devices/index.html), una configuración de AVD típica tiene:

    • Un perfil de hardware que especifica todas las funcionalidades del dispositivo (ejemplos: cámara, sensores).
    • Una imagen del Sistema, que el emulador usará para este AVD (nivel de API de destino, tales como Gingerbread o Honeycomb).
    • Una imagen de Datos que actúa como espacio de almacenamiento dedicado para los datos del usuario, las configuraciones y la tarjeta SD.
    • Otras opciones, incluidas la piel del emulador, las dimensiones de la pantalla y el tamaño de la tarjeta SD.

    Se alienta a los desarrolladores a apuntar a diferentes niveles de API, tamaños de pantalla y funcionalidades de hardware (como cámara, sensores y pantalla multitáctil). Es posible usar la configuración de AVD para personalizar el emulador según sea necesario. Los desarrolladores pueden crear tantos AVD como lo deseen, con cada uno apuntando a un dispositivo Android basado en arquitectura Intel diferente: por ejemplo, un desarrollador puede crear un AVD de Gingerbread basado en arquitectura Intel con una piel integrada, como WVGA800, o una personalizada para la cual se especificaría en forma manual la resolución de pantalla que se utilizará.

    El SDK de Android ha admitido la emulación de Android basado en arquitectura Intel desde la versión r12. El SDK integra esta compatibilidad en todas las herramientas para desarrolladores, incluido el complemento ADT. La Figura 5.6 es una captura de pantalla de muestra del emulador de Android para x86 ejecutando Gingerbread. El número de modelo está resaltado y muestra “Full Android on x86 Emulator”.


    Figura 5.5Emulador de Android

    En la siguiente documentación de Android, encontrará información detallada sobre cómo usar el emulador: http://developer.android.com/guide/developing/devices/emulator.html.

    9. ¿Qué emulador debería usar?

    Al momento de escribir este artículo, hay dos imágenes de emulador disponibles para la arquitectura Intel (x86): una para Android 2.3.7 (Gingerbread) y una para Android 4.0.4 (Ice Cream Sandwich).

    Si bien tiene muchas ventajas desarrollar para la versión de sistema operativo Android más reciente, muchos desarrolladores prefieren hacerlo para Android 2.x, ya que la mayoría de los teléfonos que están en uso actualmente todavía no tienen Android 4.x o superior (en los EE. UU., sólo 1 de cada 5 teléfonos Android tiene ICS o superior al momento de escribir este artículo). Este porcentaje cambiará con el tiempo, así que se sugiere firmemente tener presentes las condiciones del mercado al momento de determinar el sistema operativo de destino.

    El siguiente artículo puede ser útil para obtener más información del sistema operativo específica de Gingerbread: http://blogs.computerworld.com/17479/android_gingerbread_faq.

    Para Ice Cream Sandwich, se recomienda este otro: http://www.computerworld.com/s/article/9230152/Android_4.0_The_ultimate_guide_plus_cheat_sheet_.

    10. Razones para usar el emulador

    En primer lugar, es gratis. El SDK de Android y sus complementos de terceros no cuestan nada y posibilitan a los desarrolladores emular dispositivos que no poseen y a los que quizá no tengan acceso. Esto es importante porque no todos los teléfonos reciben las versiones del sistema operativo Android mediante actualizaciones por aire (Over The Air, OTA) y podría no ser factible para los desarrolladores comprar todos los dispositivos que se espera que admitan sus paquetes de software.

    Desarrollo y prueba. Los desarrolladores pueden crear con el SDK varias configuraciones de dispositivo virtual de Android* (AVD) para fines de desarrollo y prueba. Cada AVD puede tener diferentes dimensiones de pantalla, tamaños de tarjeta SD o incluso versiones del SDK de Android (lo cual es útil para probar la compatibilidad con versiones anteriores de Android).

    Jugar con una nueva versión. El emulador permite a los desarrolladores entretenerse con nuevas versiones de Android y aprender más acerca de ellas.

    Veamos ahora paso a paso cómo crear y ejecutar una imagen de emulador en una compilación x86. Por una cuestión de simplicidad, en esta sección se hará referencia al emulador de Gingerbread, aunque la mayor parte del contenido se aplica también al emulador de Ice Cream Sandwich.

    11 Creación de una imagen de emulador

    El primer paso será seguir las instrucciones de configuración que se indican aquí: http://source.android.com/source/initializing.html.

    Google* ha puesto a disponibilidad fuentes de Gingerbread en un nuevo lugar. La documentación de http://source.android.com/source/downloading.html se ha actualizado para reflejar estos cambios.

    Actualmente, las instrucciones de inicialización de repositorio predeterminadas son sólo para obtener la rama maestra o una rama específica, como cuando se usa el comando android-2.3.7_r1. Las instrucciones de repositorio y rama para crear imágenes de emulador x86 de Gingerbread no se han dado.

    Utilice la rama con la etiqueta gingerbread para descargar la rama de origen de Android más reciente, como se muestra en la Figura 5.6. Esta rama tiene los archivos y los módulos necesarios para crear imágenes del emulador x86 del SDK.


    Figura 5.6 Rama de Gingerbread

    Inicialice la compilación env, como se muestra en la Figura 5.7:


    Figura 5.7 Inicialización

    Configure con el comando lunch la compilación para crear el SDK x86, como se muestra en la Figura 5.8. Esto creará las imágenes de emulador para x86, junto con otros módulos del SDK.


    Figura 5.8 Comando lunch

    Por último, utilice el comando make sdk para iniciar la compilación, como se muestra en la Figura 5.9.


    Figura 5.9 Comando make sdk

    Además, se puede configurar la cantidad específica de trabajos paralelos para make con el parámetro –j, para acelerar el proceso de compilación (se recomienda usar un valor que sea mayor o igual a la cantidad total de CPU del sistema.)

    Se crearán tres imágenes: QEMU Android kernel image:t system.img (Android), userdata.img y ramdisk.img.

    Como se muestra en la Figura 5.10, cuando la compilación se complete, las imágenes quedarán en la carpeta de compilación $ANDROID_BUILD_TOP/out/target/product/generic_x86/


    Figura 5.10 Ubicación de las imágenes

    La imagen del kernel de Android para QEMU (kernel-qemu) viene con Android Sources. Está ubicado en la carpeta prebuilt ($ANDROID_BUILD_TOP/prebuilt/android-x86/kernel), como se observa en la Figura 5.11.


    Figura 5.11 Imagen del kernel

    Ahora ya tiene todos los archivos necesarios para ejecutar una imagen x86 de Android Gingerbread en el emulador x86 de Android. Habrá que configurar los archivos de imagen con el SDK, proceso que se tratará en la próxima sección.

    12. Cómo configurar el SDK para usar imágenes del emulador x86

    Las herramientas del SDK de Android (android, el administrador de AVD) esperan que las imágenes del emulador x86 se encuentren en las carpetas predeterminadas del SDK para imágenes de plataformas /platforms/android-10/images.

    En las capturas de pantalla de las figuras siguientes se da por supuesto que la variable de entorno $ANDROID_SDK_TOP está establecida según la ubicación de la carpeta de instalación del SDK de Android.


    Figura 5.12 Ubicación de las imágenes

    Como se ve en la Figura 5.12, Android-10 viene en forma predeterminada con imágenes de emulador para ARM. Para configurar las imágenes del emulador x86 en el SDK, es necesario crear una carpeta x86 y copiar a la carpeta las imágenes creadas. También puede mover las imágenes de ARM a su propia carpeta, como se muestra en la Figura 5.13.


    Figura 5.13 Carpeta ARM

    En la Figura 5.14 se muestran instrucciones para la carpeta x86.


    Figura 5.14 Instrucciones para x86

    En la Figura 5.15, se muestra la última carpeta de imágenes de la plataforma Android-10.


    Figura 5.15 Última carpeta de imágenes

    Antes de usar imágenes de arquitectura Intel de Gingerbread con el emulador x86, debe crear una configuración de AVD que especifique las personalizaciones necesarias de software y hardware. Más abajo se puede encontrar información detallada sobre los AVD; también en el artículo “Android* Virtual Device Emulation for Intel® Architecture” (“Emulación de dispositivo virtual de Android para Arquitectura Intel®”) de la Zona de Desarrolladores Intel.

    Ya aquí el emulador y la imagen x86 están listos para usarse. Tenga en cuenta que el rendimiento del emulador tendrá mejoras drásticas si usa el Supervisor de Ejecución Acelerada por Hardware Intel (Intel HAXM) junto con esta imagen de sistema. (Intel HAXM requiere un procesador Intel compatible con Intel VT-x. Para obtener más información acerca de Intel HAXM, visite http://int-software.intel.com/en-us/android).

    Ahora es momento de usar el emulador x86 de Gingerbread para emular una imagen x86.

    Abra la herramienta de Android o use la herramienta de creación de AVD directamente desde Eclipse.

    La Figura 5.16 y la Figura 5.17 muestran la creación de un AVD para Gingerbread con una CPU Intel® Atom™ (x86).


    Figura 5.16 Creación de un nuevo AVD


    Figura 5.17 Cuadro de diálogo de creación exitosa

    Pruebe el AVD Gingerbread x86; para ello, seleccione el AVD y haga clic en Start, como se muestra en la Figura 5.18.


    Figura 5.18 Opciones de inicio

    En la Figura 5.19 se muestra la pantalla principal de Gingerbread para Intel Atom (x86) en el emulador x86.


    Figura 5.19 Pantalla principal

    En la Figura 5.20 se muestra la vista de las configuraciones desde About Phone (Acerca del teléfono).


    Figura 5.20 Vista desde “About phone”

    Se recomienda que use el emulador x86 con aceleración de hardware de Intel® VT. Para hacer esto en Linux, se puede usar la KVM de Linux. Ubuntu tiene más documentación sobre cómo configurarla y usarla: https://help.ubuntu.com/community/KVM.


    Figura 5.21 KVM

    Con la KVM, que se muestra en la Figura 5.21, (-enable-kvm) es probable que los usuarios noten mejoras de rendimiento durante el inicio de Android y que el emulador responde con mayor rapidez.

    13. Ejemplo de prestación de Gingerbread: estadísticas de uso de batería

    En About Phone hay una sección de uso de batería, Battery Use. Las estadísticas de utilización de la batería varían según el dispositivo de emulación y la versión. En el caso de que el desarrollador pueda ingresar en el dispositivo emulado mediante telnet, hay algunos comandos simples que se pueden usar para imitar el consumo de batería. Mire en esta página un ejemplo: http://android-er.blogspot.com/2010/09/how-to-set-battery-status-of-android.html.

    14. Ejemplo de prestación de Gingerbread: administrador de tareas

    En Settings > Applications > Running Services, hay una pestaña Running que muestra los procesos y servicios en ejecución, como se muestra en la Figura 5.22.


    Figura 5.22 El administrador de tareas

    15. Ejemplo de prestación de Gingerbread: copiar y pegar texto

    Si se abre la aplicación de mensajería y se elige enviar un nuevo mensaje, el usuario puede escribir un mensaje como si enviara un SMS. Si se hace clic en el campo de texto y se escribe en el teclado del host, los caracteres aparecen con fluidez en la pantalla de Android. Después de escribir “Hello 2.3.5!”, la pantalla se ve como en la Figura 5.23.


    Figura 5.23Diversión con mensajes de texto

    Si se mueve el mouse al campo de texto donde está el mensaje “Hello 2.3.5!” y se mantiene apretado el botón del mouse (o del panel táctil) durante unos 2 segundos, aparece un menú para editar texto: Edit Text. Al elegir Select all y luego repetir la operación con el mouse, el usuario ve la opción de cortar el texto. Después de cortar el texto, si se vuelve a repetir la operación con el mouse, el usuario puede pegar el texto en su lugar original.

    16. Emulación de Ice Cream Sandwich

    La imagen de sistema del emulador x86 de Android 4.0.4 permite ejecutar una emulación de Android Ice Cream Sandwich en la máquina de desarrollo. Además del SDK de Android, las aplicaciones para Android se pueden probar en un dispositivo virtual de Android basado en la arquitectura Intel (x86).

    Para instalar la imagen de sistema del emulador, una opción es usar el Android SDK Manager (método recomendado), pero también se puede descargar el archivo zip binario y copiar el directorio incluido al directorio de complementos de su instalación del SDK de Android (este último método no admite actualizaciones automáticas del complemento).

    17. Guía de instalación

    La siguiente sección es una guía para instalar imágenes de ICS.

    17.1 Prerrequisitos

    La imagen de emulador x86 para Android necesita que esté instalado el SDK de Android. Para obtener instrucciones de instalación y configuración del SDK de Android, consulte el sitio web para desarrolladores de Android (http://developer.android.com/sdk/).

    Opcional: la imagen de emulador x86 para Android se puede acelerar con el Supervisor de Ejecución Acelerada por Hardware Intel® (Intel HAXM). Encontrará más información en el capítulo sobre Intel HAXM.

    17.2 Cómo hacer descargas por medio del Android SDK Manager

    1. Inicie el Android SDK Manager.
    2. Bajo Android 4.0.4 (puede que algunas capturas de pantalla hagan referencia a versiones anteriores), seleccione la imagen de sistema Intel x86 Atom System Image, como se muestra en la Figura 5.24.

      Figura 5.24 Imagen de sistema Intel x86 Atom
    3. Una vez instalada, haga clic en el botón de instalación Install Package.
    4. Lea el acuerdo de licencia de Intel Corporation. Si acepta los términos, seleccione Accept y haga clic en Install.
    5. El SDK Manager descargará y extraerá la imagen de sistema al lugar apropiado dentro del directorio del SDK de Android.

    17.3 Uso de la imagen de sistema

    1. Inicie el Android AVD Manager y cree un nuevo AVD (establezca el destino Target como Android 4.0.X, y CPU/ABI como Intel Atom (x86), tal cual se muestra en la Figura 5.25).

      Figura 5.25 Configuración del destino
       
      Nota: si no está disponible la opción Intel Atom (x86) para CPU/ABI, asegúrese de que la imagen de sistema se instale correctamente.
    2. Haga clic en el botón Create AVD.
    3. El AVD ya se ha creado y está listo para usarse, como se muestra en la Figura 5.26.

      Figura 5.26Imagen lista

    17.4 Descarga manual

    1. Vaya a http://www.intel.com/software/android
    2. Descargue la imagen de sistema Intel x86 Atom System Image (bajo la pestaña Tools & Downloads).
    3. Vaya al directorio que contiene el SDK de Android, como se muestra en la Figura 5.27.

      Figura 5.27 Directorio del SDK de Android
    4. El directorio system-images contiene imágenes de sistema de Android, separadas por arquitectura, como se muestra en la Figura 5.28.

      Figura 5.28 Imágenes separadas
    5. Expanda android-15 (este directorio contiene imágenes de sistema de nivel 15 de API), como se ve en la Figura 5.29.

      Figura 5.29 Nivel 15 de API
    6. Extraiga el directorio x86, contenido en el archivo de imagen de sistema descargado, directamente en el directorio android-15.
    7. La estructura del directorio debería verse ahora como en la Figura 5.30.

      Figura 5.30 Estructura esperada
    8. La imagen del sistema ya está instalada y lista para usar.

    17.5 Aceleración de la CPU

    El rendimiento de la imagen Intel Atom x86 para Android Ice Cream Sandwich se puede mejorar mediante virtualización basada en hardware con tecnología Intel.

    Si su computadora tiene un procesador Intel compatible con VT-x, se recomienda usar el Supervisor de Ejecución Acelerada por Hardware Intel (Intel HAXM) junto con esta imagen de sistema. Para obtener más información acerca de Intel HAXM, visite http://int-software.intel.com/en-us/android.

    Nota: Intel HAXM es sólo para los sistemas operativos Windows y OS X. En el caso de hosts Linux, se puede usar la máquina virtual basada en kernel (KVM) para acelerar la emulación. En la siguiente guía encontrará información sobre la instalación y configuración de KVM en Ubuntu: https://help.ubuntu.com/community/KVM/Installation.

    17.6 Aceleración de la GPU

    La imagen Intel Atom x86 para Android Ice Cream Sandwich puede aprovechar las prestaciones de GPU de hardware para mejorar el rendimiento de juegos, de programas que hagan un uso intensivo de gráficos y de elementos de la interfaz de usuario.

    Nota: la funcionalidad y el rendimiento de la aceleración de la GPU depende en gran medida de la tarjeta gráfica y los controladores de gráficos de su equipo.

    Para usar la aceleración de GPU de hardware, siga estos pasos:

    1. Abra el Android SDK Manager.
    2. Seleccione el AVD y haga clic en Edit.
    3. Aparecerá la ventana del editor de AVD. En la sección Hardware, haga clic en New, como se muestra en la Figura 5.31.

      Figure 5.31 Sección “Hardware”
    4. En la lista desplegable Property, seleccione GPU Emulation, como se observa en la Figura 5.32.

      Figura 5.32 Emulación de GPU
    5. Haga clic en OK.
    6. Después de haber agregado la propiedad GPU emulation, cambie el valor (Value) a yes, como en la Figura 5.33.

      Figura 5.33 Valor cambiado a “yes”
    7. Haga clic en Edit AVD para guardar el AVD.
    8. Después de que se haya modificado el AVD, aparecerá un cuadro de diálogo con la confirmación de la configuración del AVD. Este cuadro se muestra en la Figura 5.34.

      Figura 5.34 Cuadro de diálogo de confirmación

    En el cuadro de diálogo de confirmación, la línea hw.gpu.enabled=yes indica que la aceleración de la GPU está habilitada para ese AVD en particular.

    Nota: la aceleración de la GPU se debe habilitar para cada AVD.

  • Android Developer Learning
  • Desenvolvedores
  • Parceiros
  • Professores
  • Estudantes
  • Android*
  • Android*
  • Principiante
  • Intermediário
  • Mobilidade
  • Telefone
  • URL
  • 面向 Android* 应用的先进英特尔® C++ 编译器特性

    $
    0
    0

    目录

    在安卓系统中使用英特尔® Cilk™ Plus 运行时间库实现应用的多线程

    英特尔® Cilk™ Plus是对 C 语言和 C++ 的扩展,可快捷、轻松地利用多核和矢量处理的优势。 三个英特尔 Cilk Plus 关键词提供了简单但是功能强大的并行编程模式,运行时间和模板库为并行应用的构建提供良好的环境。

    要想使用英特尔 Cilk Plus 实现应用的多线程,必须链接至 Cilk 运行时间库(libcilkrts.so)。

    使用英特尔 C++ 编译器和 NDK build 系统(ndk-build)进行开发

    NDK build 系统未将 C++ 函数库链接至使用 C 语言编写的模块,因此,在链接过程中,编译器无法选择正确的英特尔 Cilk Plus 函数库,这将导致链接错误。

    1. 将一个 C++ 空文件添加至项目以便支持 C++ 链接至 NDK build 系统

    2. 在 Application.mk 文件中指定兼容的 C++ 实施:

    • 'APP_STL:=stlport_shared' or
    • 'APP_STL:=gnustl_static' or
    • 'APP_STL:=gnustl_shared'

    3. 按照下文“准备 JNI 调用”章节中的说明修改您的 Java 代码

    使用独立英特尔 C++ 编译器而不使用 NDK build 系统(ndk-build)进行开发

    如果您的开发环境包含 C++ 代码,您需要明确链接至 GNU_STL 库或 stlport 库。

    请按以下步骤操作:

    1. 对于 NDK 中包含的 C++ 实施的链接与编译,请指明以下标记:

    • 编译标记:
      -I$ANDROID_GNU_LIBSTDCPP/include -I$ANDROID_GNU_LIBSTDCPP/libs/x86/include
    • 链接标记(gnustl_shared):
      -L$ANDROID_GNU_LIBSTDCPP/libs/x86 -lgnustl_shared -lsupc++
    • 链接标记(gnustl_static):
      -L$ANDROID_GNU_LIBSTDCPP/libs/x86 -lgnustl_static -lsupc++

    其中,
    ANDROID_GNU_LIBSTDCPP=$NDK/sources/cxx-stl/gnu-libstdc++/4.6. 4.6 应更换为由 ANDROID_GNU_X86_TOOLCHAIN指向的 GCC 版本。 例如,如果 ANDROID_GNU_X86_TOOLCHAIN指向 $NDK/toolchains/x86-4.8/prebuilt/linux-x86,则 4.6 应更换为 4.8。
    当使用英特尔 Cilk Plus 时,您需要链接至 libcilkrts.so 库。 该库位于 /compiler/lib/ia32/gnustl 目录中。

    2. 如果使用 stlport_shared C++ 库(至少需要 NDK r9),需要添加以下标记:

    • 编译标记:
      -I$ANDROID_STLPORT_LIBSTDCPP/stlport
    • 链接标记:
      -L$ANDROID_STLPORT_LIBSTDCPP/libs/x86 -lstlport_shared

    其中
    ANDROID_STLPORT_LIBSTDCPP=$NDK/sources/cxx-stl/stlport

    如果使用英特尔 Cilk Plus,相应的 libcilkrts.so 库位于 /compiler/lib/ia32/stlport 目录中。

    准备 JNI 调用

    如果使用英特尔 Cilk Plus,则需要准备 JNI 调用。 ‘libcilkrts.so’库需要通过以下 API 调用从 Java 代码中加载:
    System.loadLibrary("cilkrts");

    如果您的应用依赖动态 C++ 实施,则需要加载 libcilkrts.so 库之外的其它相应库:

    System.loadLibrary("gnustl_shared"); 
     System.loadLibrary("cilkrts");

     System.loadLibrary("stlport_shared");
    System.loadLibrary("cilkrts"); 

    使用 PGO 提升 Android* OS 应用性能

    档案导引优化(PGO)通过重组代码布局减少指令缓存错误、并缩减代码长度及减少分支预测失误来提高应用程序性能。 PGO 向编译器提供关于常启应用的区域。 通过了解这些区域,编译器在优化应用时会更具选择性和针对性。

    相比其它操作系统,在安卓系统中使用 PGO 需要附加步骤。

    1. 在 jni/Android.mk 文件中为 C 标记添加以下选项:
    LOCAL_CFLAGS:= -prof-gen -prof-dir /sdcard

    2. 添加 WRITE_EXTERNAL_STORAGE 许可,支持应用将 PGO 输出写至 sdcard 文件夹。 将以下命令行添加至 AndroidManifest.xml 文件:
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" \>

    3. 确保配置数据成功存写。 默认模式下,应用退出时自动存写配置数据。 通常情况下 Android* 应用不会退出。 使用以下选项实施应用退出,或者解决这一问题:

    a. 选项 1:从 JAVA 代码调用退出:

    System.exit(0);

     

    b. 选项 2:从原生代码中显式输出 PGO 数据:

    #include <pgouser.h>
    	_PGOPTI_Prof_Dump_All();

     

    c. 选项 3:在应用运行过程中,使用环境变量将性能定期存写至 sdcard 文件。 让环境变量对所有应用开放,添加至 Android Image 的 init.rc 文件中:

    [bash]export INTEL_PROF_DUMP_INTERVAL 5000
    	export INTEL_PROF_DUMP_CUMULATIVE 1[/bash]

     

    注: INTEL_PROF_DUMP_INTERVAL 的测量值是微妙级,不得大于 INT_MAX。

    4. 在应用的源目录中从目标到主机复制生成的动态文件:

    [bash]adb pull ...[/bash]

     

    5. 在 Android.mk 文件中更改 C 标记以使用生成的动态文件。 您可使用 -prof-dir 参数指向不同的文件位置。
    LOCAL_CFLAGS := -prof-use

    请参考档案导引优化章节,英特尔® C++ Compiler XE 14.0 用户参考指南,在 Linux*、Windows* 和 OS X* 操作系统中使用英特尔 C++ 编译器构建应用的优化方法。

    其它相关文章与资源

    面向 Android* 的英特尔® C++ Compiler 14.0
    英特尔® System Studio - 使用英特尔® Cilk™ Plus 的多核编程
    英特尔® Cilk™ Plus
    英特尔® C++ Compiler 14.0 用户参考指南
    面向英特尔® 架构的 Android* NDK
    使用 Android* x86 NDK 与 Eclipse* 的方法以及 NDK 示例应用导入方法


    如需深入了解面向安卓开发人员的英特尔工具,请访问:面向安卓的英特尔® 开发人员专区

  • Desenvolvedores
  • Android*
  • Apple Mac OS X*
  • Linux*
  • Microsoft Windows* (XP, Vista, 7)
  • Android*
  • C/C++
  • Avançado
  • Compilador C++ Intel®
  • Telefone
  • Tablet
  • URL
  • Aumento de desempenho
  • 借助 SIMD 技术基于英特尔® 架构加快游戏代码开发

    $
    0
    0

    摘要

    总所周知,大量复杂的数学运算是 2D 和 3D 游戏开发与执行的关键基础,而且这些运算通常需要大量对计算性能要求较高的矢量与矩阵变换。 在本文中,我们将讨论矩阵乘法,并使用中国大陆流行的基于 Android* 的 3D 射击游戏“最后的防线”作为实例介绍如何使用面向英特尔® 架构(IA)的 SIMD 技术:英特尔® SIMD 流指令扩展 (英特尔® SSE[XX]) 和补充 SIMD 流指令扩展(SSSE[XX])加快数学运算、提升游戏性能。 文档结尾将介绍一些常用优化解决方案和基于英特尔架构的代码。

    背景

    简单地说,单指令多数据流(SIMD)就是在一个指令中执行多个数据计算,是指令级别的并行计算技术。 由于能够充分利用并行计算,英特尔® SSE 十分适合用于游戏代码的矢量与矩阵运算,因为矢量或矩阵中的每个元素都可以独立运算(开发人员必须检查元素确保元素之间互不影响;元素之间偶尔会出现相互影响的情况)。 如果使用传统串行计算技术,每个元素需要一个指令周期,例如,一个 4x4 矩阵需要 16 个周期才能执行所有运算。 但是如果使用 SIMD 技术,并假设 SIMD 实施可在 1 个指令周期内并行处理 4 个数据运算,这意味着 4 个元素运算可在 1 个指令周期内同步完成,所有 16 个元素运算仅需 4 个指令周期!

    英特尔 SSE 指令集广泛用于基于英特尔架构的 SIMD 实施;尤其用于游戏引擎中。 英特尔 SSE 包括很多扩展: SSE,SSE2,SSE3 和 SSE4.x,而且它们支持多种整数和浮点类型的运算。 它们还支持高效的内存访问。 在本文中,我们统统简称为“英特尔 SSE”;现在我们将介绍在矩阵乘法运算中如何使用。

    内存中有两种矩阵存储模式:

    1. 在列主序(图 1)矩阵中,所有元素在内存中是按照列顺序依次存储的。 如果内存是按照临近寻址方式访问,矩阵元素就会按照列的顺序访问。 众所周知,OpenGL* 使用这一方法在内存中存储矩阵。


    图 1. 列主序矩阵

    2. 在行主序(图 2)矩阵中,所有元素在内存中是按照行顺序依次存储的。 如果内存是按照临近寻址方式访问,矩阵元素就会按照行的顺序访问。 游戏“最后的防线”就是使用这一方法作为高级矩阵存储模式。


    图 2. 行主序矩阵

    由于本文重点介绍“最后的防线”(行主序)作为安卓架构游戏开发的使用案例,同时 OpenGL ES* (列主序)是安卓架构的唯一低级图形硬件加速 API,因此两种存储模式和相关优化我们均将介绍。

    在我们下面讨论的 OpenGL ES 和“最后的防线”中,矩阵乘法运算(矢量变换)顺序是一样的。 它们都使用“矩阵自左乘”,方程表示如下(V 为矢量,M 为矩阵):

        Vo = Mn x ... x M2 x M1 x Vi

    请参考图 3:


    图 3. MxV

    图 3 显示“MxV”结果是一个新矢量,一个 4x4 矩阵乘以一个 4 元素矢量需要 16 个乘法运算和 12 个加法运算。 这一运算负载相当大。 如果采用串行模式执行这些运算,就会需要很多指令周期,花费很长时间。 而且,游戏引擎涉及大量此类运算,因此是重点优化对象。

    在图 3 中,蓝框中的列是 4 个可同步执行的元素运算,这意味着整个 MxV 运算仅需 4 个并行乘法运算和 3 个并行加法运算。 性能因此提升 4 倍。 事实上,英特尔 SSE 非常擅长同步执行每个列中的所有乘法运算和加法运算,如图 4 所示。


    图 4. 矩阵并行运算


    图 5. MxM

    图 5 是两个矩阵相乘(MxM)的示例,它是上文介绍的矩阵乘矢量(MxV)的扩展。 但是我们应当了解一点: 这些运算受矩阵存储模式的影响。 图 5 中的不同颜色表示的是两种不同矩阵存储模式下的并行运算。 粉红色表示行主序模式下的并行运算,橙色表示列主序模式下的并行运算。 由于英特尔 SSE 还针对不同矩阵存储模式提供高效的内存访问指令集,我们应使用不同的算法来充分利用上述加速指令集。 然而必须注意内存访问指令集的内存对齐限制条件。

    下面两个章节分别介绍基于两种矩阵存储模式的两个不同解决方案。 但是都使用英特尔 SSE 并行处理矩阵运算以加快代码执行速度。

    行主序矩阵乘法优化 — 基于游戏“最后的防线”

    在使用 英特尔 SSE 优化“最后的防线”游戏引擎代码之前,我们使用英特尔® VTune™ Amplifier 2011 for Android 配置了计算开销,尤其注释了“Matrix4f::mul”函数,如图 6 所示:


    图 6. 初始(基准) Matrix4f::mul 计算开销参考

    我们使用英特尔® 凌动™ 处理器 Z2480 在 Motorola MT788 智能手机上配置了我们的代码。 特定运算执行结束后,我们发现 Matrix4f::mul 计算开销参考是 83,340,000 — 相当费时的运算。 在实际代码中显示如下:

    void Matrix4f::mul(Matrix4f *m1, Matrix4f *m2)
    	if (this != m1 && this != m2)
    	{
    
    		this->f[m00] = m1->f[m00] * m2->f[m00] + m1->f[m01] * m2->f[m10] + m1->f[m02] * m2->f[m20] + m1->f[m03] * m2->f[m30];
    		this->f[m01] = m1->f[m00] * m2->f[m01] + m1->f[m01] * m2->f[m11] + m1->f[m02] * m2->f[m21] + m1->f[m03] * m2->f[m31];
    		this->f[m02] = m1->f[m00] * m2->f[m02] + m1->f[m01] * m2->f[m12] + m1->f[m02] * m2->f[m22] + m1->f[m03] * m2->f[m32];
    		this->f[m03] = m1->f[m00] * m2->f[m03] + m1->f[m01] * m2->f[m13] + m1->f[m02] * m2->f[m23] + m1->f[m03] * m2->f[m33];
    
    		this->f[m10] = m1->f[m10] * m2->f[m00] + m1->f[m11] * m2->f[m10] + m1->f[m12] * m2->f[m20] + m1->f[m13] * m2->f[m30];
    		this->f[m11] = m1->f[m10] * m2->f[m01] + m1->f[m11] * m2->f[m11] + m1->f[m12] * m2->f[m21] + m1->f[m13] * m2->f[m31];
    		this->f[m12] = m1->f[m10] * m2->f[m02] + m1->f[m11] * m2->f[m12] + m1->f[m12] * m2->f[m22] + m1->f[m13] * m2->f[m32];
    		this->f[m13] = m1->f[m10] * m2->f[m03] + m1->f[m11] * m2->f[m13] + m1->f[m12] * m2->f[m23] + m1->f[m13] * m2->f[m33];
    
    		this->f[m20] = m1->f[m20] * m2->f[m00] + m1->f[m21] * m2->f[m10] + m1->f[m22] * m2->f[m20] + m1->f[m23] * m2->f[m30];
    		this->f[m21] = m1->f[m20] * m2->f[m01] + m1->f[m21] * m2->f[m11] + m1->f[m22] * m2->f[m21] + m1->f[m23] * m2->f[m31];
    		this->f[m22] = m1->f[m20] * m2->f[m02] + m1->f[m21] * m2->f[m12] + m1->f[m22] * m2->f[m22] + m1->f[m23] * m2->f[m32];
    		this->f[m23] = m1->f[m20] * m2->f[m03] + m1->f[m21] * m2->f[m13] + m1->f[m22] * m2->f[m23] + m1->f[m23] * m2->f[m33];
    
    		this->f[m30] = m1->f[m30] * m2->f[m00] + m1->f[m31] * m2->f[m10] + m1->f[m32] * m2->f[m20] + m1->f[m33] * m2->f[m30];
    		this->f[m31] = m1->f[m30] * m2->f[m01] + m1->f[m31] * m2->f[m11] + m1->f[m32] * m2->f[m21] + m1->f[m33] * m2->f[m31];
    		this->f[m32] = m1->f[m30] * m2->f[m02] + m1->f[m31] * m2->f[m12] + m1->f[m32] * m2->f[m22] + m1->f[m33] * m2->f[m32];
    		this->f[m33] = m1->f[m30] * m2->f[m03] + m1->f[m31] * m2->f[m13] + m1->f[m32] * m2->f[m23] + m1->f[m33] * m2->f[m33];
    	}
    	else
    	{
    		float _m00, _m01, _m02, _m03, _m10, _m11, _m12, _m13, _m20, _m21, _m22, _m23, _m30, _m31, _m32, _m33; // vars
    		// for
    		// te_mp
    		// result
    		// _matrix
    		_m00 = m1->f[m00] * m2->f[m00] + m1->f[m01] * m2->f[m10] + m1->f[m02] * m2->f[m20] + m1->f[m03] * m2->f[m30];
    		_m01 = m1->f[m00] * m2->f[m01] + m1->f[m01] * m2->f[m11] + m1->f[m02] * m2->f[m21] + m1->f[m03] * m2->f[m31];
    		_m02 = m1->f[m00] * m2->f[m02] + m1->f[m01] * m2->f[m12] + m1->f[m02] * m2->f[m22] + m1->f[m03] * m2->f[m32];
    		_m03 = m1->f[m00] * m2->f[m03] + m1->f[m01] * m2->f[m13] + m1->f[m02] * m2->f[m23] + m1->f[m03] * m2->f[m33];
    
    		_m10 = m1->f[m10] * m2->f[m00] + m1->f[m11] * m2->f[m10] + m1->f[m12] * m2->f[m20] + m1->f[m13] * m2->f[m30];
    		_m11 = m1->f[m10] * m2->f[m01] + m1->f[m11] * m2->f[m11] + m1->f[m12] * m2->f[m21] + m1->f[m13] * m2->f[m31];
    		_m12 = m1->f[m10] * m2->f[m02] + m1->f[m11] * m2->f[m12] + m1->f[m12] * m2->f[m22] + m1->f[m13] * m2->f[m32];
    		_m13 = m1->f[m10] * m2->f[m03] + m1->f[m11] * m2->f[m13] + m1->f[m12] * m2->f[m23] + m1->f[m13] * m2->f[m33];
    
    		_m20 = m1->f[m20] * m2->f[m00] + m1->f[m21] * m2->f[m10] + m1->f[m22] * m2->f[m20] + m1->f[m23] * m2->f[m30];
    		_m21 = m1->f[m20] * m2->f[m01] + m1->f[m21] * m2->f[m11] + m1->f[m22] * m2->f[m21] + m1->f[m23] * m2->f[m31];
    		_m22 = m1->f[m20] * m2->f[m02] + m1->f[m21] * m2->f[m12] + m1->f[m22] * m2->f[m22] + m1->f[m23] * m2->f[m32];
    		_m23 = m1->f[m20] * m2->f[m03] + m1->f[m21] * m2->f[m13] + m1->f[m22] * m2->f[m23] + m1->f[m23] * m2->f[m33];
    
    		_m30 = m1->f[m30] * m2->f[m00] + m1->f[m31] * m2->f[m10] + m1->f[m32] * m2->f[m20] + m1->f[m33] * m2->f[m30];
    		_m31 = m1->f[m30] * m2->f[m01] + m1->f[m31] * m2->f[m11] + m1->f[m32] * m2->f[m21] + m1->f[m33] * m2->f[m31];
    		_m32 = m1->f[m30] * m2->f[m02] + m1->f[m31] * m2->f[m12] + m1->f[m32] * m2->f[m22] + m1->f[m33] * m2->f[m32];
    		_m33 = m1->f[m30] * m2->f[m03] + m1->f[m31] * m2->f[m13] + m1->f[m32] * m2->f[m23] + m1->f[m33] * m2->f[m33];
    
    		this->f[m00] = _m00;
    		this->f[m01] = _m01;
    		this->f[m02] = _m02;
    		this->f[m03] = _m03;
    		this->f[m10] = _m10;
    		this->f[m11] = _m11;
    		this->f[m12] = _m12;
    		this->f[m13] = _m13;
    		this->f[m20] = _m20;
    		this->f[m21] = _m21;
    		this->f[m22] = _m22;
    		this->f[m23] = _m23;
    		this->f[m30] = _m30;
    		this->f[m31] = _m31;
    		this->f[m32] = _m32;
    		this->f[m33] = _m33;
    	}

    请看,这个代码简单明了。 但是显然花费时间太长,而且这个函数在游戏引擎中经常调用,因此影响了性能,亟需优化。

    如上所述,可进行如下简单的 SSE 优化(行主序):

    	__m128 m1_row_0 = _mm_setr_ps(m1->f[m00], m1->f[m01], m1->f[m02], m1->f[m03]);
    	__m128 m1_row_1 = _mm_setr_ps(m1->f[m10], m1->f[m11], m1->f[m12], m1->f[m13]);
    	__m128 m1_row_2 = _mm_setr_ps(m1->f[m20], m1->f[m21], m1->f[m22], m1->f[m23]);
    	__m128 m1_row_3 = _mm_setr_ps(m1->f[m30], m1->f[m31], m1->f[m32], m1->f[m33]);
    
    	__m128 m2_row_0 = _mm_setr_ps(m2->f[m00], m2->f[m01], m2->f[m02], m2->f[m03]);
    	__m128 m2_row_1 = _mm_setr_ps(m2->f[m10], m2->f[m11], m2->f[m12], m2->f[m13]);
    	__m128 m2_row_2 = _mm_setr_ps(m2->f[m20], m2->f[m21], m2->f[m22], m2->f[m23]);
    	__m128 m2_row_3 = _mm_setr_ps(m2->f[m30], m2->f[m31], m2->f[m32], m2->f[m33]);
    
    	__m128 out0;
    	__m128 out1;
    	__m128 out2;
    	__m128 out3;
    
    	out0 = _mm_mul_ps(m2_row_0, _mm_replicate_x_ps(m1_row_0));
    	out1 = _mm_mul_ps(m2_row_0, _mm_replicate_x_ps(m1_row_1));
    	out2 = _mm_mul_ps(m2_row_0, _mm_replicate_x_ps(m1_row_2));
    	out3 = _mm_mul_ps(m2_row_0, _mm_replicate_x_ps(m1_row_3));
    
    	out0 = _mm_madd_ps(m2_row_1, _mm_replicate_y_ps(m1_row_0), out0);
    	out1 = _mm_madd_ps(m2_row_1, _mm_replicate_y_ps(m1_row_1), out1);
    	out2 = _mm_madd_ps(m2_row_1, _mm_replicate_y_ps(m1_row_2), out2);
    	out3 = _mm_madd_ps(m2_row_1, _mm_replicate_y_ps(m1_row_3), out3);
    
    	out0 = _mm_madd_ps(m2_row_2, _mm_replicate_z_ps(m1_row_0), out0);
    	out1 = _mm_madd_ps(m2_row_2, _mm_replicate_z_ps(m1_row_1), out1);
    	out2 = _mm_madd_ps(m2_row_2, _mm_replicate_z_ps(m1_row_2), out2);
    	out3 = _mm_madd_ps(m2_row_2, _mm_replicate_z_ps(m1_row_3), out3);
    
    	out0 = _mm_madd_ps(m2_row_3, _mm_replicate_w_ps(m1_row_0), out0);
    	out1 = _mm_madd_ps(m2_row_3, _mm_replicate_w_ps(m1_row_1), out1);
    	out2 = _mm_madd_ps(m2_row_3, _mm_replicate_w_ps(m1_row_2), out2);
    	out3 = _mm_madd_ps(m2_row_3, _mm_replicate_w_ps(m1_row_3), out3);
    
    	_mm_store_ps(&this->f[0], out0);
    	_mm_store_ps(&this->f[4], out1);
    	_mm_store_ps(&this->f[8], out2);
    	_mm_store_ps(&this->f[12], out3);

    该实施是基于英特尔 SSE 内部指令。 如果编译器支持,我们建议开发人员使用 SSE 内部指令,而不要编写纯汇编语言。 与汇编语言相比,它们更具优越性,易于使用,而且不影响性能。

        __m128是支持 SSE 内部指令的数据类型。 其长度是 128 个字节,可用于存储 4 个 32 位单浮点。
        __m128 _mm_setr_ps(float z , float y , float x , float w );

        这一内部指令可为 1 个 __m128 数据设定 4 个单浮点,r0 := z, r1 := y, r2 := x, r3 := w。
        __m128 _mm_mul_ps(__m128 a , __m128 b );

        这一内部指令可并行执行 4 个单浮点“a”乘以 4 个单浮点“b”:
        r0 := a0 * b0
        r1 := a1 * b1
        r2 := a2 * b2
        r3 := a3 * b3

        _mm_replicate_(x~w)_ps是一个宏,包括:
        #define _mm_replicate_x_ps(v) \
        _mm_shuffle_ps((v), (v), SHUFFLE_PARAM(0, 0, 0, 0))

        #define _mm_replicate_y_ps(v) \
        _mm_shuffle_ps((v), (v), SHUFFLE_PARAM(1, 1, 1, 1))

        #define _mm_replicate_z_ps(v) \
        _mm_shuffle_ps((v), (v), SHUFFLE_PARAM(2, 2, 2, 2))

        #define _mm_replicate_w_ps(v) \
        _mm_shuffle_ps((v), (v), SHUFFLE_PARAM(3, 3, 3, 3))

        __m128 _mm_shuffle_ps(__m128 a , __m128 b , int i );

        这一内部指令是基于掩码“i”。 它从“a”和“ b”中选择 4 个单浮点合并一个新的基于掩码“i”的 __m128 数据。 掩码必须是一个最接近的数。 图 7 是详细规则:

        _MM_SHUFFLE(z, y, x, w)
        /* expands to the following value */
        (z<<6) | (y<<4) | (x<<2) | w


    图 7. SHUFFLE 说明

        使用以下 SHUFFLE 宏优化“最后的防线”:
        #define SHUFFLE_PARAM(x, y, z, w) \
        ((x) | ((y) << 2) | ((z) << 4) | ((w) << 6))

        这可为 1 个 __m128 数据设定 4 个相同单浮点用于同步运算同一元素值。
        #define _mm_madd_ps(a, b, c) \
        _mm_add_ps(_mm_mul_ps((a), (b)), (c))

        这一宏可首先执行乘法合并,最后执行加法,简化代码编写。
        void _mm_store_ps(float *p, __m128 a );

        这一内部指令属于内存访问。 它存储 1 个 __m128 数据至“p”地址(该地址必须是 16 字节对齐)。
        p[0] := a0
        p[1] := a1
        p[2] := a2
        p[3] := a3

    经过简单优化,我们使用英特尔 VTune Amplifier 2011 for Android 配置了同一运算,结果如图 8 所示。


    图 8. 经过优化的 Matrix4f::mul 计算开销参考

    这一计算开销参考从 83,340,000 降至 18,780,000,性能提升了 4 倍1 (我们在下述场景中执行了同样步骤与运算: 同样场面、同样敌人、同样车辆、同样武器、同样测试时长等等,但是由于 AI 和敌人数量的改变,测试结果略受影响)。 这一示例表明英特尔 SSE 并行计算能力十分强大。

    列主序矩阵乘法优化 — OpenGL ES

    对于 OpenGL ES 应用的矩阵运算,强烈推荐列主序存储模式。 该模式不仅满足 OpenGL ES 规范,而且便于并行化实施。 如上所述,开发人员可使用高效内存访问技术优化代码编写。 下面是从 ARM NEON* 到英特尔 SSE 的经典转换示例:

    void NEON_Matrix4Mul(const float* a, const float* b, float* output )
    {
        __asm__ volatile
        (
         // Store A & B leaving room for q4-q7, which should be preserved
         "vldmia %1, { q0-q3 } nt""vldmia %2, { q8-q11 }nt"
    
         // result = first column of B x first row of A
         "vmul.f32 q12, q8, d0[0]nt""vmul.f32 q13, q8, d2[0]nt""vmul.f32 q14, q8, d4[0]nt""vmul.f32 q15, q8, d6[0]nt"
    
         // result += second column of B x second row of A
         "vmla.f32 q12, q9, d0[1]nt""vmla.f32 q13, q9, d2[1]nt""vmla.f32 q14, q9, d4[1]nt""vmla.f32 q15, q9, d6[1]nt"
    
         // result += third column of B x third row of A
         "vmla.f32 q12, q10, d1[0]nt""vmla.f32 q13, q10, d3[0]nt""vmla.f32 q14, q10, d5[0]nt""vmla.f32 q15, q10, d7[0]nt"
    
         // result += last column of B x last row of A
         "vmla.f32 q12, q11, d1[1]nt""vmla.f32 q13, q11, d3[1]nt""vmla.f32 q14, q11, d5[1]nt""vmla.f32 q15, q11, d7[1]nt"
    
         // output = result registers
         "vstmia %0, { q12-q15 }"
         : // no output
         : "r" (output), "r" (a), "r" (b)     // input - note *value* of pointer doesn't change
         : "memory", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" //clobber
         );
    }
    //####################################################################################################################
    static inline void SSE_Matrix4Mul(const float* a, const float* b, float* output)
    {
    	// load matrices a and b as column-major order of OpenGL ES
    	__m128 ma_col_0 = _mm_load_ps(a);
    	__m128 ma_col_1 = _mm_load_ps(a + 4);
    	__m128 ma_col_2 = _mm_load_ps(a + 8);
    	__m128 ma_col_3 = _mm_load_ps(a + 12);
    
    	__m128 mb_col_0 = _mm_load_ps(b);
    	__m128 mb_col_1 = _mm_load_ps(b + 4);
    	__m128 mb_col_2 = _mm_load_ps(b + 8);
    	__m128 mb_col_3 = _mm_load_ps(b + 12);
    
    	// get ready to store the result
    	__m128 result0;
    	__m128 result1;
    	__m128 result2;
    	__m128 result3;
    
    	// result = first column of B x first row of A
    	result0 = _mm_mul_ps(mb_col_0, _mm_replicate_x_ps(ma_col_0));
    	result1 = _mm_mul_ps(mb_col_0, _mm_replicate_x_ps(ma_col_1));
    	result2 = _mm_mul_ps(mb_col_0, _mm_replicate_x_ps(ma_col_2));
    	result3 = _mm_mul_ps(mb_col_0, _mm_replicate_x_ps(ma_col_3));
    
    	// result += second column of B x second row of A
    	result0 = _mm_madd_ps(mb_col_1, _mm_replicate_y_ps(ma_col_0), result0);
    	result1 = _mm_madd_ps(mb_col_1, _mm_replicate_y_ps(ma_col_1), result1);
    	result2 = _mm_madd_ps(mb_col_1, _mm_replicate_y_ps(ma_col_2), result2);
    	result3 = _mm_madd_ps(mb_col_1, _mm_replicate_y_ps(ma_col_3), result3);
    
    	// result += third column of B x third row of A
    	result0 = _mm_madd_ps(mb_col_2, _mm_replicate_z_ps(ma_col_0), result0);
    	result1 = _mm_madd_ps(mb_col_2, _mm_replicate_z_ps(ma_col_1), result1);
    	result2 = _mm_madd_ps(mb_col_2, _mm_replicate_z_ps(ma_col_2), result2);
    	result3 = _mm_madd_ps(mb_col_2, _mm_replicate_z_ps(ma_col_3), result3);
    
    	// result += last column of B x last row of A
    	result0 = _mm_madd_ps(mb_col_3, _mm_replicate_w_ps(ma_col_0), result0);
    	result1 = _mm_madd_ps(mb_col_3, _mm_replicate_w_ps(ma_col_1), result1);
    	result2 = _mm_madd_ps(mb_col_3, _mm_replicate_w_ps(ma_col_2), result2);
    	result3 = _mm_madd_ps(mb_col_3, _mm_replicate_w_ps(ma_col_3), result3);
    
    	// store the result to memory
    	_mm_store_ps(output, result0);
    	_mm_store_ps(output+4, result1);
    	_mm_store_ps(output+8, result2);
    	_mm_store_ps(output+12, result3);
    }

    希望这一代码参考示例对您有所帮助。

        __m128 _mm_load_ps(float * p );
        这一内部指令从“p”地址(“p” 必须是 16 字节对齐) 到 1 个 __m128 数据加载 4 个临近单浮点数据。
        r0 := p[0]
        r1 := p[1]
        r2 := p[2]
        r3 := p[3]

    其它优化技术

    游戏代码编写还有更多优化技术与技巧。 其中一个是面向 Android* 的英特尔® C++ 编译器,这一出色、易用的工具可用来编写游戏代码的 NDK 部分。 面向安卓操作系统的英特尔 C++ 编译器可为英特尔® CPU 架构提供众多特殊优化,例如,管线、缓存和内存利用率。 我们还使用 GCC 编译代码,但是我们需要按照如下方法设置编译选项以优化性能、缓存和内存利用率:
    GCC 优化编译选项
    LOCAL_CFLAGS := -O3 -ffast-math -mtune=atom -msse3 -mfpmath=sse
    面向安卓操作系统的英特尔 C++ 编译器的优化编译选项
    LOCAL_CFLAGS := -O3 -xSSSE3_atom -ipo -no-prec-div

    工欲善其事,必先利其器。面向安卓操作系统的英特尔 VTune Amplifier 2011 可帮助开发人员快速定位程序的热点(原本十分费时),并查看缓存与内存使用状态,提高性能和质量。 英特尔® 图形性能分析器(英特尔® GPA)也是强大的工具集。 它可帮助开发人员监控整个系统的软件执行的实时状态并查找瓶颈,包括 CPU、GPU、内存、IO、图形 API,等等。 英特尔 GPA 是出色的游戏开发工具!


    图形 9. 英特尔® 图形性能分析器

    总结

    通过结合使用英特尔® SSE 和面向安卓操作系统的英特尔 C++ 编译器以及英特尔 GPA 指令集,我们显著改进了“最后的防线”的游戏性能。 在同样的测试场景中,FPS 从 30 提高到 39,约为 30%2!


    图 10. 未经优化的“最后的防线”截图(FPS 可通过游戏设置开启)


    图 11. 经过优化的“最后的防线”截图(FPS 可通过游戏设置开启)

    使用英特尔® SSE 技术为游戏代码提速极具激情和挑战。 虽然本文的介绍不够详细,但是我们希望能够启发安卓游戏开发人员充分利用 IA 相关特性优化游戏代码开发,提升游戏速度和用户体验!

    谢谢!

     

    作者简介

    YANG Yi 是来自英特尔公司的软件应用工程师,目前主攻项目是面向中国大陆、Android* 操作系统和英特尔架构(IA)开发游戏引擎并提供图形相关支持。 在众多先进英特尔® 技术的基础上,他积极推动中国大陆的独立软件厂商(ISV)交付更高性能、更高质量的游戏引擎,更多基于英特尔® x86 Android* 平台的精彩游戏产品。

    其它相关文章与资源

    基于英特尔® 架构的 Android* 模拟器的加速
    初步了解英特尔® Composer XE 2013、编译器指示与指南
    概述: 英特尔® SIMD 流指令扩展 2 (英特尔® SSE2)
    使用 #pragma SIMD 进行循环矢量化的要求
    使用 SIMD 流指令扩展创建粒子系统

     

    如需深入了解面向安卓开发人员的英特尔工具,请访问:面向安卓的英特尔® 开发人员专区

    英特尔、英特尔标识和凌动是英特尔公司在美国和/或其他国家的商标。
    版权所有 © 2013 年英特尔公司。 保留所有权利。
    *其他的名称和品牌可能是其他所有者的资产。

     

    1在性能检测过程中涉及的软件及其性能只有在英特尔微处理器的架构下方能得到优化。 诸如 SYSmark* 和 MobileMark* 等性能测试均系基于特定计算机系统、组件、软件、操作及功能。 上述任何要素的变动都有可能导致测试结果的变化。 请参考其他信息及性能测试(包括结合其他产品使用时的运行性能)以对目标产品进行全面评估。
    配置: [描述配置 + 测试内容 + 测试者]。 如欲了解更多信息,请访问:http://www.intel.com/performance

    2在性能检测过程中涉及的软件及其性能只有在英特尔微处理器的架构下方能得到优化。 诸如 SYSmark* 和 MobileMark* 等性能测试均系基于特定计算机系统、组件、软件、操作及功能。 上述任何要素的变动都有可能导致测试结果的变化。 请参考其他信息及性能测试(包括结合其他产品使用时的运行性能)以对目标产品进行全面评估。
    配置: [描述配置 + 测试内容 + 测试者]。 如欲了解更多信息,请访问:http://www.intel.com/performance

  • Desenvolvedores
  • Android*
  • Android*
  • Telefone
  • Tablet
  • URL
  • 面向 Android* KitKat 4.4 的英特尔® 凌动™ x86 映像推荐安装指南

    $
    0
    0

    介绍

    本文档可指导您安装面向 Android* KitKat 的英特尔® 凌动™ x86 映像,该映像可用于英特尔 x86 架构基础上的开发。

    前提条件

    安卓 x86 模拟器映像要求安装安卓软件开发套件(SDK)。 如需深入了解安卓软件开发套件的安装与配置,请访问安卓开发人员网站(http://developer.android.com/sdk/)。

    可选: 如需加速面向安卓的 x86 模拟器映像,请使用英特尔硬件加速执行管理器(HAXM)。 更多信息请参考本文档中的“优化”章节。

    安装

    通过 Android SDK Manager 下载

    1. 启动 Android SDK Manager。
    2. 在“Android 4.4 (API 19)”下,选择“Intel x86 Atom System Image”:
    3. 选中后,点击“Install Package”按钮。
    4. 查看英特尔公司许可协议。 如您接受所述条款,选择“Accept”并点击“Install”。
    5. SDK Manager 会将系统映像下载到 Android SDK 目录下的适当位置并解压缩。

    使用系统映像

    1. 启动安卓 AVD 管理器并创建新的 AVD,设置“Target”至“Android 4.4 – API Level 19”,并设置“CPU/ABI”至“Intel Atom (x86)”。
      面向安卓 KitKat 的英特尔凌动 x86 映像可利用硬件 GPU 特性提升游戏性能、图形密集型程序以及用户界面元素。 为了获得最佳性能,创建映像时务必检查“Use Host GPU”。
      注:GPU 加速的功能和性能很大程度上取决于您电脑上的显卡和显卡驱动程序。 GPU 加速必须在每个 AVD 基础上启用。


      注:如果“Intel Atom (x86)”CPU/ABI 选项不可用,请确保系统映像正确安装。
    2. 点击“Create AVD”按钮。
    3. AVD 已安装成功,使用就绪:

    优化

    CPU 加速

    使用基于硬件的虚拟化技术(英特尔 VT-x 技术),面向安卓 KitKat 的英特尔凌动 x86 映像的性能可得到显著提升。

    如果您的电脑采用支持 VT-x 技术的英特尔处理器,建议同时使用英特尔硬件加速执行管理器(HAXM)和这一系统映像。 如需深入了解英特尔 HAXM,请访问:http://software.intel.com/en-us/android

    注:英特尔 HAXM 仅适用于 Windows 和 OS X 操作系统。 对于 Linux 主机,可使用基于内核的虚拟机(KVM)来提升模拟性能。 如需了解在 Ubuntu 上如何配置和安装 KVM,请参考指南: https://help.ubuntu.com/community/KVM/Installation

    其它相关文章与资源

    面向 Android* Ice Cream Sandwich 的英特尔® 凌动™ x86 映像手动安装指南
    Android* 4.4 (KitKat) x86 模拟器系统映像
    面向 Android* 4.4 KitKat 的英特尔® 凌动™ x86 映像手动安装指南
    面向 Android* 开发人员的英特尔学习系列 5: 面向英特尔® 架构安装 Android* SDK
    加速编译: 第一部分: ccache

    如需深入了解面向安卓开发人员的英特尔工具,请访问:面向安卓的英特尔® 开发人员专区

  • Desenvolvedores
  • Android*
  • Android*
  • Ferramentas de desenvolvimento para Android
  • Intel Hardware Accelerated Execution Manager (HAXM)
  • Processadores Intel® Atom™
  • Telefone
  • URL

  • Intel for Android* Developers Learning Series #2:The Intel Mobile Processors

    $
    0
    0

     

    1.    Inside Medfield

    Intel® Atom™ Processor Z2610, formerly known as Medfield, shown in Figure 1, is a platform targeted for smartphones designing with Android operating system. Medfield is divided into two complexes, the North Complex and the South Complex. The North Complex consists of Saltwell, a single-core processor, a 32-bit dual channel LPDDR2 memory controller, a 3D graphics core, video decode and encode engines, a 2D display controller that is capable of supporting up to three displays, and an image processor for camera input. The South Complex of the Intel Atom Processor Z2610 consists of all the necessary I/O interfaces to complete a smartphone design, such as a security engine, a storage controller supporting SD/eMMC storage cards, a USB OTG controller, a 3G modem, Complimentary Wireless Solution (CWS) interfaces, SPI, and UART.

     

    Figure 1: Medfield Block Diagram

     

    1.1.    Saltwell, the General Picture

    Saltwell architecture is fairly simple. The idea of the design is to create a processor with a balance between optimized performance and efficient power consumption. The processor uses in-order architecture, which is different from most of the other processors in the market. The processor has a 64-KB L1 cache and a 512-KB L2 cache. This processor supports Intel® Burst Performance Technology, which lets the processor dynamically increase the CPU speed. There are three frequency modes in Saltwell: Low Frequency Mode (LFM) runs at 600 MHz, High Frequency Mode (HFM) runs at 900 MHz, and Burst Frequency Mode (BFM) runs at 1.6 GHz. Among the power optimization features, Saltwell has an ultra-low power smart L2 cache that keeps data while the CPU is in C6 states, in order to lower the latency during the resumption of C states. In addition, Saltwell has separate power planes and clock inputs for the core and the rest of the SoC, which makes power and clock gating easily configurable through Intel® Smart Idle Technology (Intel SIT). This technology enables the CPU to be switched off completely while the SoC is still in the ON state (S0 state).

    2.    Architecture Differences between Saltwell and ARM (Cortex A15)

    As listed in the book Break Away with Intel® Atom™ Processors: A guide to Architecture Migration, the Intel Atom architecture is very different from the ARM architecture in every way. Table 1 shows a list of high level differences between Saltwell and ARM Cortex architecture.

     

    Saltwell

    ARM Cortex

    Technology

    32 nm

    28 nm

    Architecture

    In-order

    Out-of-order

    Integer pipelines

    16

    15

    L1 cache

    64 KB

    Configurable up 64 KB

    L2 cache

    512 KB

    Max 4 MB

    Instruction set

    IA32, Intel® Streaming SIMD Extensions, Intel® Supplemental Streaming SIMD Extensions 3

    ARM, Thumb

    Multi Core/Thread Support

    Single core with Intel® Hyper-Threading Technology

    Multi-core

    Security Technology

    Intel® Smart & Secure Technology (Intel® S&ST)

    TrustZone* Technology

    Table 1: High Level Differences between Saltwell and ARM (Cortex A15)

    2.1.  Architecture:

    As mentioned, Saltwell has an architecture similar to other processors in the Intel Atom series. It uses an in-order execution design. With an in-order processor, all the instructions are executed according to the order they are fetched, whereas out-of-order processors are capable of executing multiple instructions simultaneously and reordering them later in the pipeline. ARM processors use out-of-order architecture, which has the advantage of executing instructions with minimal latency. However, this increases the complexity of the core design. The elimination of the reordering logic is one of the power reduction initiatives of the Intel Atom processor.

    2.2.  Integer Pipelines

    There are six phases in Intel Atom pipelines; the details are listed in Table 2.

    Phase

    Pipeline Stages

    Instruction fetch

    3

    Instruction decode

    3

    Instruction issue

    3

    Data access

    3

    Execute

    1

    Write back

    3

     

    Table 2: Intel® Atom™ Instruction Phases and Pipeline Stages

    This results in a total of 16 integer pipelines in the Intel Atom processor and three extra stages are required to execute floating point instructions. The latest ARM processor has 15 integer pipelines. The lengthy pipeline in the ARM processor trades off energy over performance. Saltwell can decode up to two instructions per clock cycle while the latest ARM processor is a triple issue superscalar architecture.

    2.3.  Instruction Sets

    ARM instruction sets are always 32-bit and aligned on a four-byte boundary whereas IA32 instruction sets vary in size and do not require any alignment. Another difference between ARM instructions and IA32 instructions is how the instruction is executed. For ARM, all the instructions are conditionally executed to reduce branch overhead and misprediction during branching. There are condition flags that each instruction needs to fulfill in order to take effect, otherwise the instruction will act as NOP and get discarded. There are conditional instructions as well in Intel architecture; these are called conditional MOV instructions. Other instructions in IA32 are not conditionally executed.

    2.4.  Multi-Core/Thread Support

    As mentioned previously, Saltwell supports Intel® Hyper-Threading Technology (Intel HT Technology) where tasks are completed by using shared resources. The details of the technology will be discussed further in the next section. ARM multi-core architecture has unique resources to perform its tasks on each core. The coherency of the cores is handled by AMBA 4 AXI*, a compatible slave interface that is directly interfaced to the core.

    2.5.  Security Technology

    There is a security subsystem in Medfield called Intel® Smart & Secure Technology (Intel S&ST) that is a complete hardware and software security architecture. This subsystem is compliant with industry standards, supporting AES, DES, 3DES, RSA, ECC, SHA-1/2, and DRM. It also supports 1000 bits of OTP and enables Secure Boot. The implementation in the ARM processor for a security system is different. There is no separate controller for the security subsystem as Intel implemented. The ARM processor uses TrustZone Technology, where resources in the system such as processor and memory are divided into two worlds: the Normal World and the Secure World. There are three motivations for this architecture: (1) to provide a security framework that allows designers to customize the functions needed depending on the use cases, (2) to save silicon area and power where there will not need to have a dedicated processor for secured tasks (3) to prevent intrusion during debug to security sensitive task in the Secure World or non-security-sensitive tasks in the Normal World, by providing a single debug component.

    3.    Intel® Hyper-Threading Technology

    Intel® Hyper-Threading Technology (Intel HT Technology) enables software to have a view of multiple logical processors in a physical processor package. Saltwell uses Intel® Hyper-Threading Technology as a boost to its performance. Having a second thread in a single in-order architecture processor enables Saltwell to execute multiple instructions within a clock cycle sharing the execution resources among the two threads, giving a 50-percent performance improvement compared to a single thread processor, as shown in Figure 2.

    Figure 2: Benefits of Intel® Hyper-Threading Technology

    In Intel HT Technology, the processor has duplicates of architecture state that consists of general purposes registers, control registers, the advanced programmable interrupt controller (APIC) registers, and some machine state registers1. The duplication of architecture states is the reason software is able to view a single core processor as two logical processors. Caches, execution units, branch predictors, control logic, and buses are shared between the two threads. This created a concern where there might be resource contention and workload imbalance between the threads. However, most of the current development kits such as Dalvik and JavaScript already have the capability to support multi-threaded environments, giving developers an easy way to generate applications that utilize the advantage of Intel HT Technology. Applications developers on Android can also utilize the Intel® VTune Performance Tool to analyze the workload and perform resource tuning on their applications.


    [1] Developers can go to http://intel.com/software/android  to find more information on porting apps to Intel Atom platform.

    [2] NDK documentation outlines compiler flags in the “ndk/docs/CPU-ARCH-ABIS.html” page.

  • Android Developer Learning
  • Desenvolvedores
  • Parceiros
  • Professores
  • Estudantes
  • Android*
  • Android*
  • Principiante
  • Intermediário
  • Telefone
  • URL
  • Intel Learning Series para desarrolladores para Android, n.º 2: Los procesadores Intel para dispositivos móviles

    $
    0
    0

    1. Dentro de Medfield

    El Procesador Intel® Atom™ Z2610, antes conocido como Medfield (Figura 1), es una plataforma creada específicamente para diseñar smartphones con sistema operativo Android. Medfield se divide en dos complejos, el Complejo Norte y el Complejo Sur. El Complejo Norte consiste de Saltwell, un procesador de núcleo único, un controlador de memoria LPDDR2 de 32 bits de doble canal, un núcleo de gráficos 3D, motores de decodificación y codificación de video, un controlador de pantalla 2D capaz de manejar hasta tres pantallas y un procesador de imágenes para datos ingresados por cámara. El Complejo Sur del Procesador Intel Atom Z2610 consiste en todas las interfaces de E/S necesarias para completar el diseño de un smartphone, tales como una imagen de seguridad, un controlador de almacenamiento que admite tarjetas SD/eMMC, un controlador USB OTG, un módem 3G, interfaces Complimentary Wireless Solution (CWS), SPI y UART.


    Figure 1. Diagrama de bloques de Medfield

    1.1 Descripción general de Saltwell

    La arquitectura Saltwell es bastante simple. La idea del diseño es crear un procesador en el que se equilibren la optimización del rendimiento y el uso eficiente de la energía. El procesador usa arquitectura “en orden”, a diferencia de la mayoría de los otros procesadores del mercado. Tiene un caché L1 de 64 KB y un caché L2 de 512 KB. Es compatible con la tecnología Intel® Burst Performance, que posibilita al procesador aumentar de forma dinámica la velocidad de la CPU. Existen tres modos de frecuencia en Saltwell: el modo de baja frecuencia (Low Frequency Mode, LFM) funciona a 600 MHz, el modo de alta frecuencia (High Frequency Mode, HFM) funciona a 900 MHz y el modo de frecuencia por ráfagas (Burst Frequency Mode, BFM) funciona a 1,6 GHz. Entre las prestaciones de Saltwell para optimizar el uso de la energía, cuenta con un smart cache L2 de ultra baja energía que conserva los datos mientras la CPU se encuentra en estados C6, a fin de reducir la latencia durante la reanudación de estados C. Además, Saltwell tiene diferentes planos de energía y entradas de reloj para el núcleo y el resto del sistema en chip (SoC), lo cual permite configurar con facilidad la selección de energía y reloj mediante Intel® Smart Idle Technology (Intel SIT). Esta tecnología posibilita apagar la CPU por completo mientras el SoC todavía se encuentra en estado ENCENDIDO (estado S0).

    2. Diferencias de arquitectura entre Saltwell y ARM (Cortex A15)

    Como se indica en el libro Break Away with Intel® Atom™ Processors: A guide to Architecture Migration (Cómo tomar el liderazgo con los procesadores Intel® Atom™: Guía para la migración de arquitecturas), la arquitectura Intel Atom es muy diferente de la arquitectura ARM en todos los aspectos. En la Tabla 1 se muestra una lista de diferencias de alto nivel entre las arquitecturas Saltwell y ARM Cortex.

     SaltwellARM Cortex
    Tecnología32 nm28 nm
    ArquitecturaEn ordenFuera de orden
    Pipelines para enteros1615
    Caché L164 KBConfigurable hasta 64 KB
    Caché L2512 KBMáx. 4 MB
    Conjunto de instruccionesIA32, Intel® Streaming SIMD Extensions, Intel® Supplemental Streaming SIMD Extensions 3ARM, Thumb
    Compatibilidad multinúcleo/multihiloUn núcleo con Intel® Hyper-Threading TechnologyMultinúcleo
    Tecnología de seguridadIntel® Smart &s; Secure Technology (Intel® S&s;ST)TrustZone* Technology

    Tabla 1: Diferencias de alto nivel entre Saltwell y ARM (Cortex A15)

    2.1 Arquitectura:

    Como ya se mencionó, Saltwell tiene una arquitectura similar a la de otros procesadores de la serie Intel Atom. Usa un diseño de ejecución “en orden”. Con un procesador en orden, todas las instrucciones se ejecutan según el orden con el que se buscan, mientras que los procesadores fuera de orden son capaces de ejecutar varias instrucciones en simultáneo y reordenarlas después en el pipeline. Los procesadores ARM usan arquitectura fuera de orden, la cual tiene la ventaja de ejecutar instrucciones con una latencia mínima. Sin embargo, esto aumenta la complejidad del diseño del núcleo. La eliminación de la lógica de reordenamiento es una de las iniciativas para la reducción del consumo de energía del procesador Intel Atom.

    2.2 Pipelines para enteros

    Hay seis fases en los pipelines de Intel Atom; los detalles se muestran en la Tabla 2.

    FaseEtapas de pipeline
    Búsqueda de instrucciones3
    Decodificación de instrucciones3
    Emisión de instrucciones3
    Acceso a datos3
    Ejecución1
    Reescritura3

    Tabla 2: Fases de instrucciones y etapas de pipeline de Intel® Atom™

    Esto da un total de 16 pipelines para enteros en el procesador Intel Atom y se requieren tres etapas adicionales para ejecutar instrucciones de punto flotante. El procesador ARM más reciente tiene 15 pipelines para enteros. Con el extenso pipeline del procesador ARM, se cede eficacia energética para favorecer el rendimiento. Saltwell puede decodificar hasta dos instrucciones por ciclo de reloj, mientras que el último procesador ARM es de arquitectura superescalar de emisión triple.

    2.3 Conjuntos de instrucciones

    Los conjuntos de instrucciones de ARM son siempre de 32 bits y alineados en un límite de cuatro bytes, mientras que los conjuntos de instrucciones de IA32 varían en tamaño y no requieren ninguna alineación. Otra diferencia entre las instrucciones de ARM y IA32 es cómo se ejecutan. Para ARM, todas las instrucciones se ejecutan condicionalmente para reducir el overhead de la rama y los errores de predicción durante el proceso de bifurcación. Hay indicadores de condición que cada instrucción debe satisfacer para tener efecto, de lo contrario la instrucción actuará como instrucción no operativa (NOP) y se la descartará. También hay instrucciones condicionales en la arquitectura Intel; se las llama instrucciones MOV condicionales. Otras instrucciones no se ejecutan condicionalmente en IA32.

    2.4 Compatibilidad multinúcleo/multihilo

    Como ya se mencionó, Saltwell es compatible con la tecnología Intel® Hyper-Threading (Intel HT), con la cual las tareas se realizan con el uso de recursos compartidos. Los detalles de esta tecnología se analizarán en la próxima sección. La arquitectura multinúcleo de ARM tiene recursos únicos para realizar sus tareas en cada núcleo. La coherencia de los núcleos está a cargo de la AMBA 4 AXI*, una interfaz esclava compatible que está interconectada con el núcleo.

    2.5 Tecnología de seguridad

    Medfield tiene un subsistema de seguridad llamado Intel® Smart & Secure Technology (Intel S&ST), una arquitectura completa de seguridad de hardware y software. Este subsistema cumple con las normas de la industria y admite AES, DES, 3DES, RSA, ECC, SHA-1/2 y DRM. También admite 1000 bits de OTP y habilita el arranque seguro. La implementación de un sistema de seguridad en el procesador ARM es diferente. No hay un controlador aparte para el subsistema de seguridad, como implementó Intel. El procesador ARM usa la tecnología TrustZone, que divide los recursos del sistema, como el procesador y la memoria, en dos mundos: el Mundo Normal y el Mundo Seguro. Hay tres razones por las que se emplea esta arquitectura: (1) para proporcionar un marco de seguridad que permita a los diseñadores personalizar las funciones necesarias según el uso, (2) reducir el uso de energía y superficie de silicio donde no haya necesidad de tener un procesador dedicado para las tareas de seguridad y (3) para prevenir la intrusión durante la depuración de tareas con riesgo de seguridad en el Mundo Seguro y tareas sin riesgo de seguridad en el Mundo Normal, mediante un único componente de depuración.

    3. Tecnología Intel® Hyper-Threading

    La tecnología Intel® Hyper-Threading (Intel HT) permite que el software vea varios procesadores lógicos en un paquete físico de procesadores. Saltwell usa la tecnología Intel® Hyper-Threading para aumentar el rendimiento. Al tener un segundo hilo en un único procesador con arquitectura en orden, Saltwell puede ejecutar múltiples instrucciones dentro de un ciclo de reloj por medio del uso compartido de recursos de ejecución entre los dos hilos; así se obtiene una mejora de rendimiento del 50 % en comparación con el procesador de un solo hilo, como se muestra en la Figura 2.

    >
    Figure 2. Beneficios de la tecnología Intel® Hyper-Threading

    Con la tecnología Intel HT, el procesador tiene duplicados del estado de la arquitectura, que consiste en registros de uso general, registros de control, los registros del controlador de interrupciones programable avanzado (APIC) y algunos registros de estado de máquina11. Gracias a la duplicación de estados de arquitectura, el software puede ver un procesador con un único núcleo como dos procesadores lógicos. Los cachés, las unidades de ejecución, los predictores de rama, la lógica de control y los buses se comparten entre los dos hilos. Esto generó la inquietud de que podría producirse contención de recursos y desequilibrio de carga de trabajo entre los hilos. Sin embargo, la mayoría de los kits de desarrollo actuales, como los de Dalvik y JavaScript, ya admiten entornos multihilo y así los desarrolladores tienen una opción sencilla para generar aplicaciones que aprovechan la ventaja de la tecnología Intel HT. Los desarrolladores de aplicaciones en Android también pueden utilizar la herramienta Intel® VTune Performance para analizar la carga de trabajo y ajustar los recursos en sus aplicaciones.


    [1] Los desarrolladores pueden encontrar más información sobre la portación de aplicaciones a la plataforma Intel Atom en http://intel.com/software/android.

    [2] La documentación del NDK incluye una descripción general de los indicadores de compilador en la página “ndk/docs/CPU-ARCH-ABIS.html”.

  • Android Developer Learning
  • Desenvolvedores
  • Parceiros
  • Professores
  • Estudantes
  • Android*
  • Android*
  • Principiante
  • Intermediário
  • Telefone
  • URL
  • Intel for Android* Developers Learning Series #3: Android Phones with Intel Processors

    $
    0
    0

     

    1.    Lava Xolo X900

    The Lava Xolo X900* was the first Android* smartphone powered by the Intel® Atom™ processor. It was released April 19, 2012 in India and based on Intel’s reference design. The phone was priced at 22,000 Rupees (INR 22,000), which was approximately 420 U.S. Dollars (USD 420) at the time of release. This is comparable in price to the GSM Samsung Galaxy Nexus*, which was released at the end of 2011 and was USD 400, or about INR 20,900, at the time of the X900’s release and the HTC One V*, which was released April 2, 2012 in India at a price of INR 19,999 or about USD 382 at the time of the X900’s release.

     

    X900

    Galaxy Nexus

    One V

    Price in USD

    420

    400

    382

    Price in INR

    22,000

    20,900

    19,999

    Exchange rate at April 19, 2012

    1.1.               Hardware

    The X900 has a 4.03-inch (600x1024) LCD display with full HD 1080p video playback. The screen is smaller than the Galaxy Nexus’ 4.65-inch (720x1280) Super AMOLED display but larger than the One V’s 3.7-inch (480x800) LCD display. The Galaxy Nexus features the same video playback, but the One V only has 720p. The X900 features an 8-megapixel rear camera with Intel® Burst Mode Technology, which allows the phone to take up to 10 photos in less than one second. It also records video in full HD 1080p and has superior image quality in low light conditions. Intel® Burst Mode Technology is similar to HTC’s Image Sense* technology found in most of their One* series phones. The Galaxy Nexus and One V both have 5-megapixel rear cameras. The X900 also features a 1.3-megapixel front camera, and Near Field Communication (NFC), which is the same as the Galaxy Nexus; however, the One V has no front-facing camera and no NFC. The X900 runs on a Z2460 1.6 GHz processor with Intel® Hyper-Threading Technology (Intel HT Technology). The Galaxy Nexus runs on a TI OMAP 4460* Dual-core 1.2 GHz Cortex-A9 and the One V runs on a Qualcomm MSM8255 Snapdragon* 1 GHz processor. The X900 device also features a 400 MHz graphics core, 1 GB of RAM and 16 GB of internal storage, putting it on par with the Galaxy Nexus and ahead of the One V, which has 512 MB of RAM and 4 GB of internal storage. The X900 does not feature a removable battery or SD card slot. The X900 has a 1460 mAh battery. The Galaxy Nexus has a 1750 mAh removable battery and no SD card slot while the One V has a 1500 mAh nonremovable battery and an SD card slot.

     

    X900

    Galaxy Nexus

    One V

    Screen

    4.03-inch (600x1024) LCD

    4.65-inch (720x1280) Super AMOLED

    3.7-inch (480x800) LCD display

    Video Playback

    1080p

    1080p

    720p

    Rear-Camera

    8-megapixel

    5-megapixel

    5-megapixel

    Front-Camera

    1.3-megapixel

    1.3-megapixel

    N/A

    NFC

    Yes

    Yes

    No

    CPU

    Z2460 1.6 GHz with Intel® HT Technology

    TI OMAP 4460* dual-core 1.2 GHz Cortex-A9

    Qualcomm MSM8255 Snapdragon* single-core 1 GHz

    GPU

    Imagination Technologies PowerVR SGX 540*

    Imagination Technologies PowerVR SGX 540*

    Qualcomm Adreno 205*

    RAM

    1 GB

    1 GB

    512 MB

    Internal Storage

    16 GB

    16 GB

    4 GB

    Battery

    1460 mAh nonremovable

    1750 mAh removable

    1500 mAh nonremovable

    SD Card

    No

    No

    Yes

    1.2. Software

    The X900 came loaded with Android 2.3.7 (Gingerbread), with no custom UI like HTC Sense* or Samsung Touchwiz*, but will be updated to Android 4.0 (Ice Cream Sandwich) later in 2012. It is unknown if the X900 will receive Android 4.1 (Jelly Bean). Although the X900 has no custom UI, it does still have some extra apps added by Lava such as the XOLO* Care app, built-in DoubleTwist music player and a custom camera app. It also features a custom widget in the notification dropdown that allows the user to quickly toggle Wi-Fi*, Bluetooth*, GPS, Auto-Sync and Auto-Brightness. The phone receives Android software updates from the manufacturer like most Android phones on the market.

    The Galaxy Nexus runs a completely stock build of Android with no added apps. At the time of the X900’s release, it ran Android 4.0.4 but has since been updated to Android 4.1. Unlike most Android phones, Nexus phones receive updates straight from Google instead of the manufacturer. For this reason, the Galaxy Nexus is the first phone to receive new versions of Android.

    The HTC One V runs Android 4.0.3 with HTC’s Sense 4.0 UI and Beats Audio* software. The Sense 4.0 UI has many unique apps and features. It has custom camera, music, car, entertainment and Internet apps, to name a few. Sense 4.0 also has many custom widgets such as bookmarks, calculator, calendar, and the popular weather clock, among others. Beats Audio is sound enhancement software that gives the user authentic sound while watching movies, playing games and listening to music while wearing headphones. The phone receives updates from HTC and will receive Android 4.1 at some point in the future.

    When it comes to software, the X900 falls behind the competition. Compared to the Galaxy Nexus, it is two Android versions behind and will likely never catch up since it receives updates from the manufacturer and not directly from Google. The X900 will likely catch up to the One V soon, but it remains to be seen which device will receive Android 4.1 first, if at all. The X900 will have a leg up on the One V with pure Android enthusiasts since it doesn’t have a custom UI, but the Galaxy Nexus is considered to be the pure Android experience.

     

    X900

    Galaxy Nexus

    One V

    Android OS

    2.3.7

    4.1

    4.0.3

    UI

    Almost Stock

    Pure Stock

    Sense 4.0

    Updates From

    Lava

    Google

    HTC

    As of July 29, 2012

    1.3.               Benchmarks

    AnTuTu Benchmark* is a benchmarking tool for Android smartphones and tablets. It tests memory performance, CPU integer performance, CPU floating point performance, 2D and 3D graphics performance, SD card reading/writing speed, and database I/O performance testing.

    Quadrant* is a benchmarking tool for Android smartphones and tablets made by Aurora Softworks. It measures CPU, Memory, I/O, and graphics performance using twelve CPU tests, one memory test, four I/O tests, one 2D graphics test, and three 3D graphics tests.

    GL Benchmark* is a cross-platform benchmarking tool. It performs graphics and computation capability tests for OpenGL ES–compliant mobile devices and embedded environments. It can test planar reflection, advanced shading system, animated water with normal maps, triangles with vertex shader texture and lighting, and space portioning and occlusion system with PVS.

     

    X900

    Galaxy Nexus

    One V

    AnTuTu

    5,720

    5,084

    2,544

    Quadrant

    3,354

    2,275

    1,980

    GL (2.1 Egypt Standard)

    3,882 (34.4 FPS)

    2,758 (24.2 FPS)

    3,605 (31.9 FPS)

    Higher scores mean better performance.

    The X900 was benchmarked with AnTuTu and Quadrant in an article on ThinkDigit.com written by Vishal Mathur. The Galaxy Nexus running Android 4.1 was benchmarked with AnTuTu and Quadrant by PhoneBuff.com. The One V was benchmarked with AnTuTu and Quadrant in an article on slashgear.com written by Ben Kersey. All GL benchmarks were pulled directly from their Web site and are average scores on August 6, 2012.

    2.    Lenovo K800*

    The Lenovo K800* was released in China on May 30, 2012. It was priced at RMB 3,299, which at the time of release was approximately $520. This is comparable in price to the Motorola RAZR V*, which was released July 19, 2012 at a price of RMB 3,298 or about USD 520 at the time of the K800s release and the Sony Xperia S*, which was released March, 2012 at a price of RMB 2,290 or about USD 519 at the time of the K800s release.

     

    K800

    RAZR V

    Xperia S

    Price in USD

    520

    520

    519

    Price in RMB

    3,299

    3,298

    2,290

    Exchange rate at May 30, 2012

    2.1.               Hardware

    The K800 has a 4.5-inch (720x1280) LCD display with full HD 1080p video playback. The RAZR V has a 4.3-inch (540x960) LCD display with full HD 1080p video playback. The Xperia S has a 4.3-inch (720x1280) LCD display with full HD 1080p video playback. The K800 features an 8-megapixel rear camera with Intel® Burst Mode Technology, which allows the phone to take up to 10 photos in less than one second. It also records video in full HD 1080p and has superior image quality in low light conditions. The RAZR V also has an 8-megapixel rear camera while the Xperia S has a 12-megapixel rear camera. Both phones can also record video in 1080P. The K800 also features a 1.3-megapixel front camera, and Near Field Communication (NFC). The RAZR V and Xperia S also feature 1.3-megapixel front cameras. The RAZR V does not have NFC while the Xperia S does. The X800 runs on a Z2460 1.6 GHz processor with Intel Hyper-Threading Technology. The RAZR V runs on a 1.2 GHz TI OMAP 4430 dual core processor. The Xperia S runs on a 1.5 GHz Qualcomm MSM8260* dual core processor. The K800 also features a 400 MHz graphics core, 1 GB of RAM and 16 GB of internal storage. The RAZR V features an Imagination PowerVR SGX540* GPU, 1 GB of RAM and 4 GB of internal storage. The Xperia S features an Adreno 220* GPU, 1 GB of RAM and 32 GB of internal storage. The K800 has a 1900 mAh nonremovable battery and an SD card slot. The RAZR V and Xperia S both have a 1750 mAh nonremovable battery and an SD card slot.

     

     

    K800

    RAZR V

    Xperia S

    Screen

    4.5-inch (720x1280) LCD

    4.3-inch (540x960) LCD

    4.3-inch (720x1280)

    Video Playback

    1080p

    1080p

    1080p

    Rear-Camera

    8-megapixel

    8-megapixel

    8-megapixel

    Front-Camera

    1.3-megapixel

    1.3-megapixel

    1.3-megapixel

    NFC

    Yes

    No

    Yes

    CPU

    Z2460 1.6 GHz with Intel® HT Technology

    1.2 GHz TI OMAP 4430 dual core

    1.5 GHz Qualcomm MSM8260* dual core

    GPU

    Imagination Technologies PowerVR SGX 540*

    Imagination PowerVR SGX540*

    Adreno 220*

    RAM

    1 GB

    1 GB

    1 GB

    Internal Storage

    16 GB

    4 GB

    32 GB

    Battery

    1900 mAh nonremovable

    1750 mAh nonremovable

    1750 mAh nonremovable

    SD Card

    Yes

    Yes

    Yes

    2.2.  Software

    The K800 comes with Android 2.3 (Gingerbread) and a custom Lenovo* UI. The custom UI is heavily modified from stock Android. The menus, home screens, and standard apps are all different from stock Android, and it has its own widgets and apps. The K800 should be upgraded to Android 4.0 (Ice Cream Sandwich) in the future but it is unknown if it will receive Android 4.1 (Jelly Bean). The K800 receives updates from Lenovo.

    The RAZR V comes with Android 4.0 and Motorola’s custom UI. It is expected to receive Android 4.1 in the future. The Custom UI is much closer to stock Android than Motorola’s previous UI, MotoBlur*. It has its own custom icons and widgets and slight changes to the app drawer. The RAZR V receives updates from Motorola.

    The Xperia S launched with Android 2.3, but was updated to Android 4.0 in the second quarter of 2012 and has Sony’s custom UI. It is unknown whether it will receive Android 4.1. The custom UI is close to stock Android but has a few added features such as Overview Mode*, which allows you to pinch out on the screen and see all of the active widgets on one screen. It also displays notifications on the lock-screen such as Facebook* events. There are also many custom Sony widgets not available in other UIs.

    In the software department, the K800 is at a slight disadvantage since it is still running Android 2.3 while its competitors are running 4.0. Since all of these phones feature custom UIs it is a matter of preference as to which one is the best; however stock Android enthusiasts will likely choose the RAZR V or Xperia S since they are closer to stock Android than the K800.

     

    K800*

    RAZR V

    Xperia S

    Android OS

    2.3.7

    4.0.4

    4.0.4

    UI

    LeOS*

    Motorola UI

    Sony UI

    Updates From

    Lenovo

    Motorola

    Sony

    As of July 29, 2012

    2.3.  Benchmarks

    AnTuTu Benchmark is a benchmarking tool for Android smartphones and tablets. It tests memory performance, CPU integer performance, CPU floating point performance, 2D and 3D graphics performance, SD card reading/writing speed, and database I/O performance testing.

    Quadrant is a benchmarking tool for Android smartphones and tablets made by Aurora Softworks. It measures CPU, Memory, I/O, and graphics performance using twelve CPU tests, one memory test, four I/O tests, one 2D graphics test, and three 3D graphics tests.

    GL Benchmark is a cross-platform benchmarking tool. It performs graphics and computation capability tests for OpenGL ES–compliant mobile devices and embedded environments. It can test planar reflection, advanced shading system, animated water with normal maps, triangles with vertex shader texture and lighting, and space portioning and occlusion system with PVS.

     

    K800

    RAZR V

    Xperia S

    AnTuTu

    5,335

    N/A

    6,466

    Quadrant

    3,850

    N/A

    3,062

    GL (2.1 Egypt Standard)

    2,913 (25.8 FPS)

    N/A

    3,365 (29.8 FBS)

    Higher scores mean better performance.

    The K800 was benchmarked with AnTuTu in an article on netbooknews.com written by Nicole Scott. The Xperia S was benchmarked on AnTuTu by PhoneArena.com in February while it was still running Android 2.3. The K800 was benchmarked with Quadrant in an article on Engaget.com written by Richard Lai. The Xperia S was benchmarked on Quadrant by PhoneArena.com in February while it was still running Android 2.3. All GL benchmarks were pulled directly from their Web site and are average scores on September 2, 2012.

    3.    Orange San Diego*

    The third smartphone powered by Intel technology, the Orange San Diego*, was released in the United Kingdom on June 6, 2012. Also based on the Intel reference design, this phone is almost identical to the Xolo X900. The price at release was 199 British pounds (GBP 199), which at release was about USD 306. This is comparable in price to the HTC Desire C*, which was released in early June 2012 and priced at GBP 189.99 or about USD 292 at June 6, 2012. It is also comparable in price to the Sony Xperia Go*, released in mid-July 2012 and priced at GBP 229 or about USD 352 using the exchange rate at June 6, 2012.

     

    San Diego

    Desire C

    Xperia Go

    Price in USD

    306

    292

    352

    Price in GBP

    199

    189.99

    229

    Exchange rate at June 6, 2012

    3.1.  Hardware

    The San Diego has a 4.03-inch (600x1024) LCD display with full HD 1080p video playback. The Desire C and Xperia Go both have 3.5-inch (320x480) screens with no HD video playback. The Xperia Go has a scratch-, dust-, and water-resistant screen. The San Diego features an 8-megapixel rear camera with Intel® Burst Mode Technology, which allows the phone to take up to 10 photos in less than one second. It also records video in full HD 1080p and has superior image quality in low light conditions. Intel Burst Mode Technology is similar to HTC’s Image Sense technology found in most of their One series phones. The San Diego also features a 1.3-megapixel front camera and Near Field Communication (NFC). The Desire C and Xperia Go both have 5-megapixel rear cameras and no front-facing cameras. They also both have NFC. The San Diego runs on a Z2460 1.6 GHz processor with Intel Hyper-Threading Technology. The Desire C has a 600 MHz Qualcomm MSM7227A Snapdragon* Cortex-A5 processor. The Xperia Go has a 1 GHz NovaThor* U8500 Dual-core Cortex A9 processor. The San Diego also features a 400 MHz graphics core, 1 GB of RAM and 16 GB of internal storage. The Desire C features an Adreno 200* GPU, 512 MB of RAM and 4 GB of internal storage. The Xperia Go features a Mali-400* GPU, 512 MB of RAM and 8 GB of internal storage. The San Diego has a 1460 mAh nonremovable battery and there is no SD card slot. The Desire C has a 1230 mAh removable battery and an SD card slot. The Xperia Go has a 1305 mAh nonremovable battery and an SD card slot.

     

    San Diego

    Desire C

    Xperia Go

    Screen

    4.03-inch (600x1024) LCD

    3.5-inch (320x480) HVGA

    3.5-inch (320x480) TFT LCD

    Video Playback

    1080p

    Not HD

    Not HD

    Rear-Camera

    8-megapixel

    5-megapixel

    5-megapixel

    Front-Camera

    1.3-megapixel

    N/A

    N/A

    NFC

    Yes

    Yes

    Yes

    CPU

    Z2460 1.6 GHz with Intel® HT Technology

    Qualcomm MSM7227A Snapdragon* single-core 600 MHz Cortex-A5

    1 GHz NovaThor* U8500 dual-core Cortex A9

    GPU

    Imagination Technologies PowerVR SGX 540*

    Qualcomm Adreno 200*

    ARM Holdings Mali-400*

    RAM

    1 GB

    512 MB

    512 MB

    Internal Storage

    16 GB

    4 GB

    8 GB

    Battery

    1460 mAh nonremovable

    1230 mAh removable

    1305 mAh nonremovable

    SD Card

    No

    Yes

    Yes

    3.2.               Software

    The San Diego runs Android 2.3 (Gingerbread) with a custom UI by Orange, which is different from the custom UI on the K800. It receives updates from Orange and should be updated to Android 4.0 (Ice Cream Sandwich) in the future.

    The Desire C runs Android 4.0 (Ice Cream Sandwich) with the Sense 4.0 UI and Beats Audio software. The Sense 4.0 UI has many unique apps and features. It has custom camera, music, car, entertainment and Internet apps, to name a few. Since 4.0, it also has many custom widgets such as bookmarks, calculator, calendar, and the popular weather clock among others. Beats Audio is sound enhancement software that gives the user authentic sound while watching movies, playing games, and listening to music while wearing headphones. It receives updates from HTC.

    The Xperia Go runs Android 2.3.7 with a custom UI by Sony. The custom UI is close to stock Android but has a few added features such as Overview Mode, which allows you to pinch out on the screen and see all of the actives widgets on one screen. It also displays notifications on the lock-screen such as Facebook events. There are also many custom Sony widgets not available in other UIs. It receives updates from Sony and should be receiving Android 4.0 later this year.

    When it comes to software, the San Diego is slightly behind the Desire C since it is still on Android 2.3, but is on par with the Xperia Go. It remains to be seen whether the San Diego or the Xperia Go will receive Android 4.0 first, but they will both catch up to the Desire C soon. Since none of these smartphones receive updates straight from Google, it is unknown which smartphone will receive Android 4.1 first, or if they will at all. The Xperia Go will have a leg up over the San Diego and Desire C with pure Android enthusiasts since its UI is closest to stock.

     

    San Diego

    Desire C

    Xperia Go

    Android* OS

    2.3.7

    4.0.3

    2.3.7

    UI

    Orange UI

    Sense 4.0

    Sony UI

    Updates From

    Orange

    HTC

    Sony

    As of July 29, 2012

    3.3.   Benchmarks

    AnTuTu Benchmark is a benchmarking tool for Android smartphones and tablets. It tests memory performance, CPU integer performance, CPU floating point performance, 2D and 3D graphics performance, SD card reading/writing speed, and database I/O performance testing.

    Quadrant is a benchmarking tool for Android smartphones and tablets made by Aurora Softworks. It measures CPU, Memory, I/O, and graphics performance using twelve CPU tests, one memory test, four I/O tests, one 2D graphics test, and three 3D graphics tests.

    GL Benchmark is a cross-platform benchmarking tool. It performs graphics and computation capability tests for OpenGL ES–compliant mobile devices and embedded environments. It can test planar reflection, advanced shading system, animated water with normal maps, triangles with vertex shader texture and lighting, and space portioning and occlusion system with PVS.

     

    San Diego

    Desire C

    Xperia Go

    AnTuTu

    5,602

    1,929

    5,628

    Quadrant

    4,127

    1,452

    2,375

    GL (2.1 Egypt Standard)

    28 FPS

    2,740 (24.2 FPS)

    60 FPS

    Higher scores mean better performance.

    The San Diego was benchmarked with AnTuTu, Quadrant, and GL Benchmark in an article on theverge.com written by Aaron Souppouris. The Desire C was benchmarked with AnTuTu and Quadrant in an article on gsmdome.com written by Mircea Vasile. Desire C GL benchmark was pulled directly from their Web site and are average scores on August 6, 2012. The Xperia Go was benchmarked with AnTuTu, Quadrant, and GL Benchmark in an article on reviews.cnet.co.uk written by Natasha Lomas.

    Intel, the Intel logo, and Intel Atom are trademarks of Intel Corporation in the United States and other countries.

    *Other names and brands may be claimed as the property of others.

  • Intel for Android Developers Learning Series
  • Desenvolvedores
  • Parceiros
  • Professores
  • Estudantes
  • Android*
  • Android*
  • Avançado
  • Principiante
  • Intermediário
  • Telefone
  • URL
  • Intel Learning Series para desarrolladores para Android*, n.º 3: Teléfonos Android con procesadores Intel

    $
    0
    0

    1. Lava Xolo X900

    El Lava Xolo X900* fue el primer smartphone Android con procesador Intel® Atom™. Salió a la venta el 19 de abril de 2012 en la India y se basa en el diseño de referencia de Intel. Su precio era de 22.000 rupias (INR 22.000), que equivalía aproximadamente a 420 dólares estadounidenses (USD 420) en la fecha de su lanzamiento. Este precio es comparable al del Samsung Galaxy Nexus* GSM, que llegó al mercado a fines de 2011 y costaba USD 400, unas INR 20.900, al momento del lanzamiento del X900, y al del HTC One V*, que salió a la venta el 2 de abril del 2012 en la India a un precio de INR 19.999, o unos USD 382 al 19 de abril de ese año.

     X900Galaxy NexusOne V
    Precio en USD420400382
    Precio en INR22.00020.90019.999

    Tasa de cambio al 19 de abril de 2012

    1.1 Hardware

    El X900 tiene una pantalla LCD de 4,03 pulgadas (600 x 1024) con reproducción de video full HD 1080p. La pantalla es más pequeña que la Super AMOLED de 4,65 pulgadas (720 x 1280) del Galaxy Nexus One, pero más grande que la pantalla LCD de 3,7 pulgadas (480 x 800) del One V. El Galaxy Nexus tiene las mismas características de reproducción de video, pero el One V sólo tiene 720p. El X900 cuenta con una cámara posterior de 8 megapíxeles con tecnología de disparo continuo Intel® Burst Mode, que permite al teléfono tomar hasta 10 fotos en menos de un segundo. También graba video en full HD 1080p y tiene una imagen de calidad superior en ambientes de poca luz. La tecnología Intel® Burst Mode es similar a la tecnología Image Sense* de HTC que tienen la mayoría de los teléfonos de su serie One*. Tanto el Galaxy Nexus como el One V tienen cámaras posteriores de 5 megapíxeles. El X900 también cuenta con una cámara delantera de 1,3 megapíxeles y comunicación de campo cercano (NFC), al igual que el Galaxy Nexus; por su parte, el One V no tiene cámara delantera ni NFC. El X900 utiliza un procesador Z2460 de 1,6 GHz con tecnología Hyper-Threading de Intel® (Intel HT). El Galaxy Nexus se sirve de un procesador TI OMAP 4460* Cortex-A9 de doble núcleo a 1,2 GHz, y el One V, de un Qualcomm MSM8255 Snapdragon* a 1 GHz. El X900 posee también un núcleo de gráficos de 400 MHz, 1 GB de RAM y 16 GB de espacio de almacenamiento interno, a la par del Galaxy Nexus y por encima del One V, que tiene 512 MB de RAM y 4 GB de espacio de almacenamiento interno. El X900 no tiene batería extraíble ni ranura para tarjeta SD. La batería que lleva es de 1460 mAh. El Galaxy Nexus tiene una batería extraíble de 1750 mAh y no incluye ranura para tarjeta SD, mientras que el One V viene con batería no extraíble de 1500 mAh y ranura para tarjeta SD.

     X900Galaxy NexusOne V
    PantallaLCD de 4,03” (600 x 1024)Super AMOLED de 4,65” (720 x 1280)LCD de 3,7”(480 x 800)
    Reproducción de video1080p1080p720p
    Cámara posterior8 megapíxeles5 megapíxeles5 megapíxeles
    Cámara delantera1,3 megapíxeles1,3 megapíxelesNo tiene
    NFCNo
    CPUZ2460 a 1,6 GHz con tecnología Intel® HTTI OMAP 4460* Cortex-A9 de núcleo doble a 1,2 GHzQualcomm MSM8255 Snapdragon* de un núcleo a 1 GHz
    GPUImagination Technologies PowerVR SGX 540*Imagination Technologies PowerVR SGX 540*Qualcomm Adreno 205*
    RAM1 GB1 GB512 MB
    Almacenamiento interno16 GB16 GB4 GB
    Batería1460 mAh no extraíble1750 mAh extraíble1500 mAh no extraíble
    Tarjeta SDNoNo

    1.2. Software

    El X900 venía cargado con Android 2.3.7 (Gingerbread), sin interfaz de usuario personalizada como el HTC Sense* o el Samsung Touchwiz*, pero se lo actualizará a Android 4.0 (Ice Cream Sandwich) en lo que resta de 2012. Se desconoce si recibirá Android 4.1 (Jelly Bean). Aunque no tiene interfaz de usuario personalizada, sí incluye algunas aplicaciones extra agregadas por Lava, como XOLO* Care, reproductor de música DoubleTwist incorporado y una aplicación personalizada para la cámara. También trae un widget propio en la lista desplegable de notificación, que permite al usuario alternar rápidamente entre Wi-Fi*, Bluetooth*, GPS, sincronización automática y brillo automático. Recibe actualizaciones de Android del fabricante, como la mayoría de los teléfonos Android del mercado.

    El Galaxy Nexus utiliza la versión estándar de Android sin aplicaciones adicionales. Al momento del lanzamiento del X900, usaba Android 4.0.4, pero desde entonces se ha actualizado a Android 4.1. A diferencia de la mayoría de los teléfonos Android, los Nexus reciben actualizaciones directas de Google, no del fabricante. Por esta razón, el Galaxy Nexus es el primer teléfono en recibir las versiones nuevas de Android.

    El HTC One V utiliza Android 4.0.3 con la interfaz de usuario Sense 4.0 de HTC y el software Beats Audio*. La interfaz de usuario Sense 4.0 tiene muchas aplicaciones y prestaciones exclusivas. Viene con aplicaciones exclusivas para la cámara, para reproducir música, para el auto, de entretenimiento y para Internet, por nombrar algunas. Sense 4.0 también incluye muchos widgets propios, tales como favoritos, calculadora, calendario y el popular Weather Clock, entre otros. Beats Audio es un software de mejora de sonido que ofrece al usuario un sonido auténtico mientras mira películas, juega o escucha música con auriculares. El teléfono recibe actualizaciones de HTC y se actualizará a Android 4.1 en el futuro.

    En cuanto al software, el X900 queda detrás de sus competidores. En comparación con el Galaxy Nexus, está dos versiones de Android detrás y es posible que nunca lo alcance, ya que recibe actualizaciones del fabricante y no directamente de Google. Es probable que el X900 alcance pronto al One V, pero queda por ver cuál recibirá primero Android 4.1, si es que llegan a recibirlo. El X900 tendrá ventaja sobre el One V entre los entusiastas del Android puro, puesto que no viene con interfaz de usuario personalizada, aunque se considera que la verdadera experiencia de Android puro es el Galaxy Nexus.

     X900Galaxy NexusOne V
    Versión de Android2.3.74.14.0.3
    Interfaz de usuarioCasi estándarEstándar puraSense 4.0
    Actualiza desdeLavaGoogleHTC

    Al 29 de julio de 2012

    1.3 Bancos de pruebas

    AnTuTu Benchmark* es una herramienta de pruebas para smartphones y tabletas Android. Evalúa el rendimiento de la memoria, el rendimiento de la CPU para enteros, el rendimiento de la CPU para punto flotante, el rendimiento de gráficos 2D y 3D, la velocidad de lectura y escritura en tarjetas SD, y el rendimiento de E/S de bases de datos.

    Quadrant* es una herramienta de pruebas para smartphones y tabletas Android creada por Aurora Softworks. Mide el rendimiento de la CPU, la memoria, entrada/salida y los gráficos; para ello usa doce pruebas de CPU, una de memoria, cuatro de E/S, una de gráficos 2D y tres de gráficos 3D.

    GL Benchmark* es una herramienta de pruebas para varias plataformas. Realiza pruebas de gráficos y de capacidad de cálculo para dispositivos móviles OpenGL ES y entornos integrados. Puede evaluar reflexión planar, sistema de sombreado avanzado, animación de agua con mapas normales, triángulos con textura, sombreado e iluminación en vértices, y sistema de división y oclusión de espacio con PVS.

     X900Galaxy NexusOne V
    AnTuTu5.7205.0842.544
    Quadrant3.3542.2751.980
    GL (2.1 Egypt Standard)3.882 (34,4 fps)2.758 (24,2 fps)3.605 (31,9 fps)

    Los puntajes más altos indican mejor rendimiento.

    El X900 se sometió a prueba con AnTuTu y Quadrant en un artículo de ThinkDigit.com escrito por Vishal Mathur. PhoneBuff.com utilizó AnTuTu y Quadrant para probar el Galaxy Nexus con Android 4.1. El One V se probó con AnTuTu y Quadrant en un artículo de slashgear.com escrito por Ben Kersey. Todos los puntajes de GL se tomaron directamente de su sitio web y son promedios del 6 de agosto de 2012.

    2. Lenovo K800*

    El Lenovo K800* salió a la venta en China el 30 de mayo de 2012. Su precio era de RMB 3.299, que en ese momento equivalía aproximadamente a USD 520. Este precio es comparable al del Motorola RAZR V*, que entró en el mercado el 19 de julio de 2012 a un precio de RMB 3.298 o unos USD 520 a la fecha de lanzamiento del K800s, y al del Sony Xperia S*, que ingresó en el mercado en marzo de 2012 a un precio de RMB 2.290 o unos USD 519 a la fecha de lanzamiento del K800s.

     K800RAZR VXperia S
    Precio en USD520520519
    Precio en RMB3.2993.2982.290

    Tasa de cambio al 30 de mayo de 2012

    2.1 Hardware

    El K800 tiene una pantalla LCD de 4,5 pulgadas (720 x 1280) con reproducción de video full HD 1080p. El RAZR V trae una pantalla LCD de 4,3 pulgadas (540 x 960) con reproducción de video full HD 1080p. Por su parte, el Xperia S tiene una pantalla LCD de 4,3 pulgadas (720 x 1280) con reproducción de video full HD 1080p. El K800 cuenta con una cámara posterior de 8 megapíxeles con tecnología de disparo continuo Intel® Burst Mode, que permite al teléfono tomar hasta 10 fotos en menos de un segundo. También graba video en full HD 1080p y tiene una imagen de calidad superior en ambientes de poca luz. El RAZR V también tiene una cámara posterior de 8 megapíxeles, mientras que la del Xperia S es de 12 megapíxeles. Ambos teléfonos también pueden grabar video en 1080p. El K800 cuenta además con una cámara delantera de 1,3 megapíxeles y comunicación de campo cercano (NFC). El RAZR V y el Xperia S también traen cámaras delanteras de 1,3 megapíxeles. El RAZR V no tiene NFC, pero el Xperia S sí. El K800 utiliza en procesador Z2460 a 1,6 GHz con tecnología Intel Hyper-Threading. El RAZR V funciona con un procesador TI OMAP 4430 de doble núcleo a 1,2 GHz. El, por su parte, Xperia S funciona con un Qualcomm MSM8260* de doble núcleo a 1,5 GHz. El K800 viene además con un núcleo de gráficos de 400 MHz, 1 GB de RAM y 16 GB de espacio de almacenamiento interno. El RAZR V trae una GPU Imagination PowerVR SGX540*, 1 GB de RAM y 4 GB de espacio de almacenamiento interno. El Xperia S ofrece una GPU Adreno 220*, 1 GB de RAM y 32 GB de espacio de almacenamiento interno. El K800 se vende con una batería de 1900 mAh no extraíble y ranura para tarjeta SD. Tanto el RAZR V como el Xperia S tienen una batería de 1750 mAh no extraíble y ranura para tarjeta SD.

     K800RAZR VXperia S
    PantallaLCD de 4.5” (720 x 1280)LCD de 4.3” (540 x 960)4.3” (720 x 1280)
    Reproducción de video1080p1080p1080p
    Cámara posterior8 megapíxeles8 megapíxeles8 megapíxeles
    Cámara delantera1,3 megapíxeles1,3 megapíxeles1,3 megapíxeles
    NFCNo
    CPUZ2460 a 1,6 GHz con tecnología Intel® HTTI OMAP 4430 a 1,2 GHz con doble núcleoQualcomm MSM8260* a 1,5 GHz con doble núcleo
    GPUImagination Technologies PowerVR SGX 540*Imagination PowerVR SGX540*Adreno 220*
    RAM1 GB1 GB1 GB
    Almacenamiento interno16 GB4 GB32 GB
    Batería1900 mAh no extraíble1750 mAh no extraíble1750 mAh no extraíble
    Tarjeta SD

    2.2. Software

    El K800 viene con Android 2.3 (Gingerbread) y una interfaz de usuario propia de Lenovo. Esta interfaz tiene muchas modificaciones respecto de la estándar de Android. Los menús, las pantallas de inicio y las aplicaciones estándares son diferentes y tiene sus propios widgets y aplicaciones. El K800 se debería actualizar a Android 4.0 (Ice Cream Sandwich) en el futuro, pero no se sabe si recibirá Android 4.1 (Jelly Bean). Las actualizaciones las recibe de Lenovo.

    El RAZR V viene con Android 4.0 y la interfaz de usuario propia de Motorola. Se espera que reciba Android 4.1 en el futuro. La interfaz de usuario es mucho más parecida a la estándar de Android que la anterior de Motorola, la MotoBlur*. Tiene sus propios íconos y widgets, y hay algunos cambios en el conjunto de aplicaciones. Las actualizaciones las recibe de Motorola.

    El Xperia S salió a la venta con Android 2.3, pero se lo actualizó a Android 4.0 en el segundo trimestre de 2012 y tiene la interfaz de usuario propia de Sony. No se sabe si recibirá Android 4.1. La interfaz de usuario es muy parecida a la estándar de Android, pero tiene algunas prestaciones adicionales, como el Overview Mode*, que permite ver todos los widgets activos en la pantalla con un pellizco de pantalla. También muestra notificaciones en la pantalla de bloqueo, como eventos de Facebook*. También hay muchos widgets de Sony no disponibles en otras interfaces de usuario.

    En cuanto al software, el K800 corre con una ligera desventaja porque todavía usa Android 2.3 mientras que sus competidores ya tienen el 4.0. Como todos estos teléfonos tienen interfaces de usuario personalizadas, es una cuestión de preferencia determinar cuál es mejor; sin embargo, es probable que los entusiastas de Android prefieran el RAZR V o el Xperia S, ya que están más cerca del Android estándar que el K800.

     K800*RAZR VXperia S
    Versión de Android2.3.74.0.44.0.4
    Interfaz de usuarioLeOS*Motorola UISony UI
    Actualiza desdeLenovoMotorolaSony

    Al 29 de julio de 2012

    2.3. Bancos de pruebas

    AnTuTu Benchmark es una herramienta de pruebas para smartphones y tabletas Android. Evalúa el rendimiento de la memoria, el rendimiento de la CPU para enteros, el rendimiento de la CPU para punto flotante, el rendimiento de gráficos 2D y 3D, la velocidad de lectura y escritura en tarjetas SD, y el rendimiento de entrada/salida de bases de datos.

    Quadrant es una herramienta de pruebas para smartphones y tabletas Android creada por Aurora Softworks. Mide el rendimiento de la CPU, la memoria, entrada/salida y los gráficos; para ello usa doce pruebas de CPU, una de memoria, cuatro de entrada/salida, una de gráficos 2D y tres de gráficos 3D.

    GL Benchmark es una herramienta de pruebas para varias plataformas. Realiza pruebas de gráficos y de capacidad de cálculo para dispositivos móviles OpenGL ES y entornos integrados. Puede evaluar reflexión planar, sistema de sombreado avanzado, animación de agua con mapas normales, triángulos con textura, sombreado e iluminación en vértices, y sistema de división y oclusión de espacio con PVS.

     K800RAZR VXperia S
    AnTuTu5.335N/D6.466
    Quadrant3.850N/D3.062
    GL (2.1 Egypt Standard)2.913 (25,8 fps)N/D3.365 (29,8 fps)

    Los puntajes más altos indican mejor rendimiento.

    El K800 se sometió a prueba con AnTuTu en un artículo de netbooknews.com escrito por Nicole Scott. PhoneArena.com probó el Xperia S con AnTuTu en febrero, mientras todavía tenía Android 2.3. El K800 se probó con Quadrant en un artículo de Engaget.com escrito por Richard Lai. PhoneArena.com probó el Xperia S con Quadrant en febrero, mientras todavía tenía Android 2.3. Todos los puntajes de GL se tomaron directamente de su sitio web y son promedios del domingo 2 de septiembre de 2012.

    3. Orange San Diego*

    El tercer smartphone con tecnología Intel, el Orange San Diego*, salió al mercado del Reino Unido el 6 de junio de 2012. También se basa en el diseño de referencia de Intel y es casi idéntico al Xolo X900. Su precio en esa fecha era de 199 libras británicas (GBP 199), que equivalía a USD 306. Este valor es comparable al del HTC Desire C*, lanzado en junio de 2012 a GBP 189,99 o unos USD 292 al 6 de junio de 2012. También es comparable al del Sony Xperia Go*, lanzado a mediados de julio de 2012 y con un precio de GBP 229 o unos USD 352 con la tasa de cambio del 6 de junio de 2012.

     San DiegoDesire CXperia Go
    Precio en USD306292352
    Precio en GBP199189,99229

    Tasa de cambio al 6 de junio de 2012

    3.1. Hardware

    El San Diego tiene una pantalla LCD de 4,03 pulgadas (600 x 1024) con reproducción de video full HD 1080p. El Desire C y el Xperia Go tienen ambos pantallas de 3,5 pulgadas (320 x 480) sin reproducción de video HD. La pantalla del Xperia Go es resistente a los rayones, el polvo y el agua. El San Diego cuenta con una cámara posterior de 8 megapíxeles con tecnología de disparo continuo Intel® Burst Mode, que permite al teléfono tomar hasta 10 fotos en menos de un segundo. También graba video en full HD 1080p y tiene una imagen de calidad superior en ambientes de poca luz. La tecnología Intel Burst Mode es similar a la tecnología Image Sense de HTC que tienen la mayoría de los teléfonos de su serie One. El San Diego cuenta además con una cámara delantera de 1,3 megapíxeles y comunicación de campo cercano (NFC). Tanto el Desire C como el Xperia Go tienen cámara posterior de 5 megapíxeles y no traen cámara delantera. También ofrecen NFC. El San Diego utiliza un procesador Z2460 a 1,6 GHz con tecnología Intel Hyper-Threading. El Desire C está equipado con un procesador Qualcomm MSM7227A Snapdragon* Cortex-A5 a 600 MHz. En el caso del Xperia Go, el procesador es un NovaThor* U8500 Cortex A9 de doble núcleo a 1 GHz. El San Diego viene además con un núcleo de gráficos de 400 MHz, 1 GB de RAM y 16 GB de espacio de almacenamiento interno. El Desire C ofrece una GPU Adreno 200*, 512 MB de RAM y 4 GB de espacio de almacenamiento interno. El Xperia Go cuenta con una GPU Mali-400*, 512 MB de RAM y 8 GB de espacio de almacenamiento interno. El San Diego tiene una batería de 1460 mAh no extraíble y no incluye ranura para tarjeta SD. El Desire C se vende con una batería de 1230 mAh extraíble y ranura para tarjeta SD. El Xperia Go trae una batería de 1305 mAh no extraíble y ranura para tarjeta SD.

     San DiegoDesire CXperia Go
    PantallaLCD de 4,03” (600 x 1024)HVGA de 3,5” (320 x 480)LCD TFT de 3,5” (320 x 480)
    Reproducción de video1080pNo HDNo HD
    Cámara posterior8 megapíxeles5 megapíxeles5 megapíxeles
    Cámara delantera1,3 megapíxelesN/DN/D
    NFC
    CPUZ2460 a 1,6 GHz con tecnología Intel® HTQualcomm MSM7227A Snapdragon* Cortex-A5 de un núcleo a 600 MHzNovaThor* U8500 Cortex A9 de doble núcleo a 1 GHz
    GPUImagination Technologies PowerVR SGX 540*Qualcomm Adreno 200*ARM Holdings Mali-400*
    RAM1 GB512 MB512 MB
    Almacenamiento interno16 GB4 GB8 GB
    Batería1460 mAh no extraíble1230 mAh extraíble1305 mAh extraíble
    Tarjeta SDNo

    3.2 Software

    El San Diego utiliza Android 2.3 (Gingerbread) y una interfaz de usuario propia de Orange, diferente de la que utiliza el K800. Recibe actualizaciones de Orange y se debería actualizar a Android 4.0 (Ice Cream Sandwich) en el futuro.

    El Desire C viene con Android 4.0 (Ice Cream Sandwich), la interfaz de usuario Sense 4.0 y el software Beats Audio. La interfaz de usuario Sense 4.0 tiene muchas aplicaciones y prestaciones exclusivas. Viene con aplicaciones exclusivas para la cámara, para reproducir música, para el auto, de entretenimiento y para Internet, por nombrar algunas. Desde la versión 4.0, también incluye muchos widgets propios, tales como favoritos, calculadora, calendario y el popular Weather Clock, entre otros. Beats Audio es un software de mejora de sonido que ofrece al usuario un sonido auténtico mientras mira películas, juega o escucha música con auriculares. Recibe actualizaciones de HTC.

    El Xperia Go funciona con Android 2.3.7 y trae una interfaz de usuario propia de Sony. La interfaz de usuario es muy parecida a la estándar de Android, pero tiene algunas prestaciones adicionales, como el Overview Mode*, que permite ver todos los widgets activos en la pantalla con un pellizco de pantalla. También muestra notificaciones en la pantalla de bloqueo, como eventos de Facebook. También hay muchos widgets de Sony no disponibles en otras interfaces de usuario. Recibe actualizaciones de Sony y debería actualizarse a Android 4.0 durante este año.

    En cuanto al software, el San Diego está ligeramente por debajo del Desire C, ya que todavía usa Android 2.3, pero está a la par del Xperia Go. Resta por ver entre el San Diego y el Xperia Go cuál recibirá primero Android 4.0, pero ambos alcanzarán pronto al Desire C. Como ninguno de estos smartphones recibe actualizaciones directas de Google, no se sabe cuál recibirá primero Android 4.1, o si llegarán a recibirlo. El Xperia Go tendrá ventaja sobre el San Diego y el Desire C entre los entusiastas del Android puro, puesto que su interfaz de usuario es la más parecida a la estándar.

     San DiegoDesire CXperia Go
    Versión de Android2.3.74.0.32.3.7
    Interfaz de usuarioOrange UISense 4.0Sony UI
    Actualiza desdeOrangeHTCSony

    Al 29 de julio de 2012

    3.3 Bancos de pruebas

    AnTuTu Benchmark es una herramienta de pruebas para smartphones y tabletas Android. Evalúa el rendimiento de la memoria, el rendimiento de la CPU para enteros, el rendimiento de la CPU para punto flotante, el rendimiento de gráficos 2D y 3D, la velocidad de lectura y escritura en tarjetas SD, y el rendimiento de entrada/salida de bases de datos.

    Quadrant es una herramienta de pruebas para smartphones y tabletas Android creada por Aurora Softworks. Mide el rendimiento de la CPU, la memoria, entrada/salida y los gráficos; para ello usa doce pruebas de CPU, una de memoria, cuatro de entrada/salida, una de gráficos 2D y tres de gráficos 3D.

    GL Benchmark es una herramienta de pruebas para varias plataformas. Realiza pruebas de gráficos y de capacidad de cálculo para dispositivos móviles OpenGL ES y entornos integrados. Puede evaluar reflexión planar, sistema de sombreado avanzado, animación de agua con mapas normales, triángulos con textura, sombreado e iluminación en vértices, y sistema de división y oclusión de espacio con PVS.

     K800RAZR VXperia S
    AnTuTu5.6021.9295.628
    Quadrant4.1271.4522.375
    GL (2.1 Egypt Standard)28 fps2.740 (24,2 fps)60 fps

    Los puntajes más altos indican mejor rendimiento.

    El San Diego se probó con AnTuTu, Quadrant y GL Benchmark en un artículo de theverge.com escrito por Aaron Souppouris. El Desire C se probó con AnTuTu y Quadrant en un artículo de gsmdome.com escrito por Mircea Vasile. El puntaje de GL del Desire C se tomó directamente de su sitio web y son promedios del 6 de agosto de 2012. El Xperia Go se sometió a prueba con AnTuTu, Quadrant y GL Benchmark en un artículo de reviews.cnet.co.uk escrito por Natasha Lomas.

    Intel, el logotipo de Intel e Intel Atom son marcas comerciales de Intel Corporation en los Estados Unidos y otros países.
    *Es posible que la propiedad de otros nombres y marcas corresponda a terceros.

  • Intel for Android Developers Learning Series
  • Desenvolvedores
  • Parceiros
  • Professores
  • Estudantes
  • Android*
  • Android*
  • Avançado
  • Principiante
  • Intermediário
  • Telefone
  • URL
  • Editor's App Picks January 2014 - Best of SYAP

    $
    0
    0

    We recently launched the "Share Your App Project" on the Intel Developer Zone as a way to encourage developers to share emerging and innovative app projects with our community.  Each month we will recognize standout apps for being innovative, creative and effectively using technology and tools.  If you'd like to get recognition and community feedback on your best projects in concept, under development, in testing or published, follow this link and let us know what you are working on.

    This month, we take a look at 5 projects, all which stand out by leveraging new technology and developer ingenuity to deliver amazing computing experiences.

    Published Projects


    • Beautify: get on Google Play  
      App Description: "Look your best! Create the most flattering possible photo for Facebook, Twitter, or online dating sites. Beautify will automatically find a face in a photo, detect its features, and give you an instant makeover. Additionally, the complexion control lets you accurately match your skin tone, or experiment with tanning and lightening. Beautify will help you to look good and project the image that you want to create.  It uses the latest facial attractiveness technology to enhance your portrait photos. It does so by analyzing the face to locate features such as eyes, nose and mouth; and compares this with a model derived from the world's most attractive people. It applies these characteristics to your photos and yet retains all the features that make a person unique. The result is usually a pleasing improvement with better skin tone, brighter eyes, lips and teeth and enhanced facial symmetry."

      Editors Notes:  Beautify is an amazingly simple app on the surface, but under the hood sits a sophisticated set of computational algorithms and complex facial detection models that musters all the CPU horsepower of a modern mobile device.  The result is a fun and entertaining app that allows us to realize a more beautiful images from not so flattering photography . In addition, this app was originally compiled for ARM-based devices then recompiled with x86 libraries to run on the latest Intel-powered Android devices.  This app truly symbolizes how powerful processing combined with ingenious coding and business-minded development can deliver everyday value in the palm of your hand.

    • Babylonian Twins: get on Google Play   
      App Description: "Solve difficult puzzles and find hidden treasures in one of the most challenging puzzle platformers. Babylonian Twins takes you to 576 BC in ancient Mesopotamia with beautifully reconstructed historic environments, authentic original Middle Eastern music and innovative two-character control."

      Editors Notes: This app stands out for a couple of reasons. This app has a LONG history going back to Commodore Amiga days.  Many of us have a fondness for Commodore systems, however when you consider an game that old that has new life and is as relevant and entertaining to play today as it was back in the day, you have to have respect.  The cooperative character play and platformer puzzle scenarios are very familiar for us today however WAY ahead of its time for an Amiga game.  The other stand out aspect of this game is how it was ported from ARM to x86.  Some ports are easy and some require some work. This was the latter. Like many challenging ports we often find a bug in the code that was not fully realized until running on a different architecture.  With some code sleuthing the developer found an error in the PNGLib file and corrected. So kudos for the new work done on PNGLib and for the old work done to allow us to experience Babylonian Twins on Intel powered Android devices.

    Projects In Testing


    • Nika Digitalfrom Studio Mercato  
      App Description: "Nika is an abstract strategy game closely modeled after accurate ancient Greek battle tactics. / / Two to four players race to reach their allied city’s gates, positioned across from them. The first player to reach their victory area across the board wins.

      Editors Notes: Nika is a new kind of retro modern app. It is modern in that it is leveraging the latest in HTML5 technology allowing a common code source to be used and optimized for various platforms. It is also a retro experience in that it is a digital board game, but you can do so much more than you can with the typical board game, allowing you to move troops in groups. Nika then stands out when played on the right device.  We've played Nika on a number of devices and while it is a great experience on both handhelds and laptops we found that Nika is something special when played on All in One tabletop PC devices.  Here members can sit around the device in family style boardgame play.  This experience is unique, bringing newer digital age technology back to a more traditional face to face multi-player scenario.  Developers: take note of what Nika is doing well here.  We suspect there is much more to this.

    Projects Under Development


    • askMama
      App Description: "A social good app that allows expecting mothers with any type of cell phone (dumb or smart) to subscribe to text tips from MAMA or ask MAMA volunteers questions about their pregnancy."

      Editors Notes: askMAMA was developed during our NYC Hackathon, and won the Best Social App category. This app has gotten the attention of the UN Foundation and looks to be moving further than our event. The app has a lot of potential to help new mothers get access to quality medical information from the most basic of connected feature phones, while at the same time allowing those with knowledge and information to connect with those around the world in need of their help.  


    • Hammerfield
      App Description: "Can you break the record for the longest spacewalk? Strap yourself into a jetpack and cruise around the space station! Smash asteroids and debris with your hammer to protect the ISS and maximize your fuel. Guard the resupply capsules as they deliver more fuel to you. How will your spacewalk stack up against humanity's best?"

      Editors Note: This app also was developed during the hackathon at the NYC Android Codefest.  This app stood out because it was clear the idea was just formed during the Codefest then rapidly prototyped using Construct 2 then packaged and tested using the Intel XDK. As the day progressed we saw the game take shape from simple game play using basic primitives to being fine tuned with polished graphics. After one day they had a very good demo of the game working at the hackathon.  This app is a great example of quality rapid development pairing a developer and artist.  We hope to see the work on Hammerfield continue.

    Imagem do ícone: 

  • Android*
  • HTML5
  • Telefone
  • Tablet
  • Desenvolvedores
  • Parceiros
  • Professores
  • Estudantes
  • Android*
  • Viewing all 343 articles
    Browse latest View live


    <script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>