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

HTML5标准与性能之四:asm.js

$
0
0

之前的几篇文章分别介绍了WebWorkersTyped ArrayParallelArray,最后,我们再来介绍一下与性能相关的标准:asm.js。

asm.js

asm.js是由Mozilla提出的一个基于JS的语法标准,主要是为了解决JS引擎的执行效率问题,尤其是使用Emscripten从C/C++语言编译成JS的程序的效率,目前只有Mozilla的Firefox Nightly中支持。

Emscripten

Emscripten是Mozilla的一个实验性项目,目的是把C/C++开发的应用编译成JS或HTML5的应用,编译过程中需要首先把C/C++程序编译成LLVM的中间代码,然后再转换成JS代码,这样做的主要原因是可以很好地复用现有的针对LLVM的优化。

C/C++是一种强类型的语言,这很好地对应了不同字长的CPU指令,每一种数据类型都有固定的上下限,一旦计算超出这个上下限就会产生溢出,比如char类型的取值范围是[-128,127],而(char)(127 + 1)这个计算就会溢出,得到(char)-128

JS语言不仅是弱类型的,而且数值类型只有一种-NumberNumber类型的数据采用双精度64位格式的IEEE 754值表示。如果用JS模拟C/C++类型的数值计算,就要模拟各种类型数据计算时的溢出效果。我们通过下面这个简单的C程序来看看如何用JS来模拟这样的计算。

char xInt8 = 127;
char yInt8 = xInt8 + 1; // 溢出:yInt8 == (char) -128
cahr zInt8 = xInt8 / 2; // 舍入:zInt8 == (char) 63 

上面这段代码通过JS模拟后的代码如下:

var xInt8 = 127; // (1)
var $add = (xInt8 + 1) | 0; // (2)
var yInt8 = ($add << 24) >> 24; // (3)
var $div = ((yInt8 | 0) / 2) & -1; // (4)
var zInt8 = ($div << 24) >> 24; // (5) 
  1. 8位整型变量127,相当于char xInt8 = 127;
  2. X|0让计算结果成为32位整数,此时$add == 128
  3. 先左移24位再右移24位,让第8位成为32位整数的符号位,来模拟8位整数计算,此时yInt8 == -128
  4. JS中127/2结果是浮点数63.5,利用X&-1将结果转化成32位整数63(-1的补码表示就是0xFFFFFFFF)
  5. 用上面(3)相同的方法,把结果转换成8位整数

大家看到,利用一些位移和逻辑运算可以模拟C/C++语言中的数据计算,Emscripten就利用这个方法将C代码转换成JS代码。大家可能还记得前篇文章介绍过的Typed Array,对Typed Array元素赋值则会自动进行相应的溢出和舍入处理,因此,利用Typed Array还可以改写成以下的代码:

var HEAP8 = new Int8Array(STACK_SIZE); // 构造一个Int8Array数组
HEAP8[0] = 127; // char xInt8 = 127
HEAP8[1] = HEAP[0] + 1; // char yInt8 = xInt8 + 1,此时yInt8是-128
HEAP8[2] = HEAP[1] / 2; // char zInt8 = xInt8 / 2 

在EmScripten中,Typed Array用来模拟C/C++中的堆栈以及指针的访问。

语法

asm.js不是一种新的语言,而是JS语法的一个子集,也就是说所有用asm.js写的程序都是合法的JS程序,asm.js与JS语言的关系有点类似C与C++的关系。因此,不支持asm.js的浏览器或JS引擎也可以无误地执行asm.js的代码。

asm.js顾名思义是作为JS的汇编语言来设计的,它的语法手写起来非常困难,且难以阅读。首先,asm.js的语法利用了一些标注让JS的变量成为强类型的,这些标注与Emscripten生成的代码如出一辙,实际上asm.js的产生就是为了提高Emscripten转换后的代码执行效率的。我们来看一个例子:

intValue = f1() | 0; // 利用或运算(|)标记函数f1返回值为int32整数
floatValue = +f2(); // 用加号(+)标记函数f2返回值为双精度型浮点 

同时,asm.js还规定了一个特殊的语法格式,下面这段代码是一个最简单的asm.js示例(代码来自:http://asmjs.org/spec/latest/):

function MyAsmModule(stdlib, foreign, heap) {
"use asm"; // "use asm"来告诉JS引擎这个函数采用asm.js编译器解析执行
// module body...
return { // 返回向外暴露的函数接口
 export1: f1,
 export2: f2,
 // ... };
}
var result = MyAsmModule({}, {}, null).export1(); // 调用函数export1 

在这个例子中,参数stdlib、foreign、heap由外部传入,表示: 1. stdlib:有限的标准库函数,主要是一些数学函数,对应Math对象上的方法 2. foreign:foreign function interface (FFI)外部JS函数访问接口 3. heap:传入一个ArrayBuffer对象,作为asm.js的堆

编译和运行

由于asm.js相当于支持了强类型,因此可以直接对应编译成机器指令执行。asm.js的代码采用另外一套AOT(Ahead Of Time)编译器,将asm.js代码预先编译成机器指令,在编译过程或运行过程中,一旦发现语法错误或违反类型标记的情况出现,便重新将代码交予JS引擎解析执行(见下图)。

Linking图片来自:http://asmjs.org/spec/latest/

性能

JS一直以来被人诟病的一个方面就是它的性能,得益于这些年来浏览器之间的竞争,让JS的性能大大提升,Google的V8、Mozilla的SpiderMonkey以及微软的Chakra在性能方面都已经相当不错,而asm.js进一步提升到相对本地代码2倍慢的性能(如下图)。这些测试用例使用Emscripten转换而来,Emscripten已经可以直接生成asm.js代码。 Performance数据来自:http://ejohn.org/blog/asmjs-javascript-compile-target/

Demo

参考

  1. asm.js specification: http://asmjs.org/spec/latest/
  2. IEEE 754: https://en.wikipedia.org/wiki/IEEE_floating_point
  • html5
  • asm.js
  • performance
  • emscripten
  • Developers
  • Partners
  • Professors
  • Students
  • Android*
  • Apple iOS*
  • Apple Mac OS X*
  • Linux*
  • Microsoft Windows* 8
  • Tizen*
  • Android*
  • HTML5
  • Tizen*
  • HTML5
  • JavaScript*
  • Intermediate
  • Microsoft Windows* 8 Style UI
  • Optimization
  • URL
  • Code Sample
  • Improving performance

  • Apresentações da Intel no TDC 2013 em Floripa

    $
    0
    0

    Durante os dias 24, 25 e 26 de Maio de 2013, participamos do The Developers Conference 2013 em Florianópolis. Foi um excelente evento onde tivemos a oportunidade de encontrar pessoalmente muitos desenvolvedores e trocar muitas informações com todos eles.

    Quem passou pelo stand da Intel pode ver algumas demonstrações bem legais sobre Perceptual Computing, e pode ainda tirar as dúvidas sobre o Perceptual Challenge Brasil, competição que anunciamos durante a abertura do evento. Se teve sorte, pode ainda sair do stand com um dos nossos Paper Toys distribuídos durante o evento.


    Com três dos nossos Community Managers, pudemos fazer oito palestras durante os três dias de evento, e os slides utilizados nelas podem ser encontrados abaixo:

    George Silva:

    Felipe Pedroso:

    Jomar Silva:

    Icon Image: 

    Attachments: 

    http://software.intel.com/sites/default/files/blog/393109/toys.jpg
    http://software.intel.com/sites/default/files/blog/393109/androidsemgastarenergia.pdf
    http://software.intel.com/sites/default/files/blog/393109/perc-presentation.pdf
    http://software.intel.com/sites/default/files/blog/393109/ultrabooks-sensores.pdf
    http://software.intel.com/sites/default/files/blog/393109/cp-apps.pdf
    http://software.intel.com/sites/default/files/blog/393109/hybrid-apps.pdf

    Meshcentral.com - New Direct Routing

    $
    0
    0

    Meshcentral.com is of course a cloud service, but it can also be run as an Intranet service. I do exactly that within Intel and so, I get a bunch of users that give me feedback about the Intranet version of Meshcentral.com from time-to-time. Well, I supported two ways of routing traffic to Intel AMT... using a another node as traffic relay or use Intel AMT Client Initiated Remote Access (CIRA). Someone gave me feedback last week that within the Intranet he could not access his lone machine, this was surprising since the Intranet version of Meshcentral has direct connectivity and would not have to do any complicated routing to perform management operations. With all the cloud techniques I use, I never bothered to support the simplest routing of them all. So this week, I added "direct routing" from the server to the nodes.

    I still have a flaw with my implementation... I realized it last night. This new direct routing to Intel AMT only works if the Mesh Agent is alive and running to report it's presense to the server. So, there is a blog about a new feature... but I still have work to do to make it fully work.

    In the picture below, we see all 3 ways Meshcentral can route traffic to Intel AMT. CIRA only works passed NAT routers, traffic relay works passed NAT's and HTTPS proxies. The direct routing could be useful if computers are exposed with a public IP address, or at least the Intel AMT ports.

    Ylian
    Meshcentral.com

  • Mesh
  • MeshCentral
  • MeshCentral.com
  • Intel AMT
  • AMT
  • Intel vPro
  • vPro
  • routing
  • direct
  • Direct Routing
  • Traffic Routing
  • Ylian
  • Icon Image: 

  • Known Issues
  • Marketing
  • Product Documentation
  • Product Support
  • Technical Article
  • Tutorial
  • #HTML5培训体会#

    $
    0
    0

    前不久,我和几十位高校、企业同行一道参加了汇博-英特尔HTML5培训课程,通过这一课程我们了解了HTML5 这一应用程序开发领域的未来趋势,初步掌握了HTML5及一些先进的跨平台开发工具,并和英特尔、微软以及PHP中国等国内外名企的资深专家进行了愉快而有成效的面对面交流,这必将有助于各位尤其是高校教师跟上行业发展步伐,进而让所在高校的学生受益。

    感谢两家企业为我们提供的高质量的培训和交流机会,期待他们为中国的IT教育做出更大的贡献。


    金东

    jdong@126.com

  • HTML5 教育 培训
  • Icon Image: 

  • News
  • A Intel e o HTML5

    $
    0
    0

    Desde que comecei a trabalhar como Community Manager de HTML5 aqui na Intel, muita gente me pergunta o motivo da Intel apoiar o HTML5.

    "Nossa visão de futuro é um mundo no qual os desenvolvedores podem criar incríveis experiências em plataforma cruzada, que passam livremente de dispositivo para dispositivo e de tela para tela, um mundo em que os aplicativos podem atingir um número maior de clientes e podem ser lançados no mercado mais rapidamente, sem limitações."

    Basta olhar ao seu redor que verá isso com clareza. Provavelmente agora mesmo enquanto você está lendo isso, está cercado por dispositivos eletrônicos através dos quais você consome e produz informações no seu dia a dia. Talvez você não tenha notado ainda, mas os serviços que você consome com maior frequência, provavelmente são aqueles que te propiciam uma experiência contínua, independente de dispositivo. Se ainda não percebeu isso, atente para as redes sociais. As redes mais usadas na atualidade, em maior ou menor grau, te entregam esta experiência: você interage na rede através de seu PC, Smartphone, TV ou Tablet de forma tão parecida, que por vezes você nem percebe que trocou de dispositivo. Há ainda casos onde um serviço que foi criado com um dispositivo em mente (como filmes pela Internet em PCs), acaba sendo mesmo usado em um cenário bem diferente deste (filmes pela Internet assistidos na TV da sala de casa, acessados e controlados por um vídeo game).

    Se do lado usuário, você quer sempre a melhor experiência compartilhada entre dispositivos, do lado desenvolvedor isso pode ser um pesadelo. São diversos dispositivos e cada um deles possui seu sistema operacional, seu SDK, sua linguagem de programação e seus “truques” para fazer as coisas funcionarem como esperado.

    O HTML5 ajuda muito a reduzir a complexidade deste cenário, pois com uma única base de código, você já consegue suportar diversas plataformas, entregando aos usuários uma experiência contínua de uso, sem que você seja obrigado a manter inúmeras versões do seu software, em diversas linguagens e sistemas operacionais. Mais do que isso, utilizando frameworks (polyfills) e bibliotecas já existentes, você consegue acessar recursos específicos de cada dispositivo, aumentando ainda mais a integração do seu sistema com eles, sem necessariamente aumentar a complexidade de desenvolvimento e manutenção do seu código.

    Para saber mais sobre HTML5 e sobre os motivos que levam a Intel a gostar tanto dele, recomendo a leitura deste documento, em Português. Depois de ler o documento, acredito que você vai ter uma visão bem mais ampla sobre o HTML5 e sobre o seu papel no futuro da indústria de tecnologia.

    Se já conhece HTML5 ou se tem apenas uma noção básica dele, recomendo uma visita à nossa página de HTML5 do Intel Developer Zone. Ali você vai encontrar diversos exemplos de aplicativos multiplataforma (com código fonte disponibilizado), além de ferramentas e serviços gratuitos para desenvolvimento, testes, depuração e empacotamento de Apps HTML5 para diversas plataformas e dispositivos móveis. Se tiver dúvidas, use nosso Fórum de HTML5, também em Português para esclarece-la.

    Icon Image: 

    Speeding Up the Android* Emulator on Intel® Architecture

    $
    0
    0

    Abstract:

    If you are an Android* developer who is unhappy with the performance of the Android emulator, then this document is for you. Over and over again, we have heard from many Android developers that the emulator is slow and painful to work with, but this should not be the case! If you are using a fairly up-to-date computer with an Intel® processor that has Intel® Virtualization Technology enabled running Microsoft Windows* or Apple Mac OS*, then you can use the Intel® Hardware Accelerated Execution Manager (Intel® HAXM), or KVM for Linux*, to accelerate the Android Emulator by an order of magnitude very easily, which will speed-up your testing and debugging of your Android applications. This document explains all the steps required to accelerator the emulator and how to work with it. We then explain how to use the NDK to compile x86 native code and the correct way to submit APKs containing x86 native libraries to the Google Play store. Intel HAXM is also used to accelerate the Tizen* emulator, but this is out of scope in this documentation. For more information, go to tizen.org within the SDK section.

    Contents

    1. Introduction
    2. Installation
    2.1. Prerequisites
    2.2. Installation on Windows
    2.3. Installation on Linux
    2.3.1. Installation of KVM
    2.4. Creating an AVD (Android* Virtual Device)
    3. Best Known methods
    3.1. Testing your application with the emulator from Eclipse
    3.2. Submitting multiple APKs for different ABIs vs. submitting fat binaries to Google Play
    3.3. Compile your NDK for x86
    3.3.1. Adding the path of NDK to your Environment Variable
    3.3.2. Compiling with the NDK
    3.3.3. Another way of compiling with the NDK

    1. Introduction

    This document will guide you through installing the Intel® Hardware Accelerated Execution Manager (Intel® HAXM), a hardware-assisted virtualization engine (hypervisor) that uses Intel® Virtualization Technology (Intel® VT) to speed up Android* development on Windows*. It also explains how to setup a hardware-assisted KVM on Linux* and best known methods in compiling natively and submitting apps to the Google Play Store for x86.

    2. Installation

    2.1. Prerequisites

    • You need to have the Android SDK installed.
    • Your computer must have an Intel processor with support for Intel VT-x, EM64T and Execute Disable(XD) Bit functionality enabled from the BIOS.

    2.2. Installation on Windows

    After you have installed the Android SDK, open the SDK Manager. In the extras section, you can find the Intel HAXM.

    Check the box and click the ‘Install packages…’ button, once you have installed the package, the status will appear as ‘Installed’, which is misleading as this is not the case. The SDK only copies the Intel HAXM executable on your machine, and it is up to you to install the executable.

    To install the Intel HAXM executable, search your hard drive for IntelHaxm.exe (or IntelHAXM.dmg on Mac OS X). If you left everything to default, it should be located at C:\Program Files\Android\android-sdk\extras\Intel\Hardware_Accelerated_Execution_Manager\IntelHaxm.exe.

    Intel HAXM only works in combination with one of the Intel® Atom™ processor x86 system images, which are available for Android 2.3.3 (API 10), 4.0.3 (API 15), 4.1.2 (API 16), 4.2.2 (API 17). These Intel system images can be installed exactly the same way as the ARM-based images via the SDK manager.

    When you click on the IntelHaxm executable, a welcome screen is displayed like this:

    You can adjust how much RAM memory is allocated to Intel HAXM. After you do this, click Next. The next screen confirms the memory allocation. If everything is as you wish, click Install.

    In order to be able to install the Intel HAXM, you need to have Intel VT-x enabled in your BIOS, otherwise you will get an error like this during install:

    If you get this error, go to your BIOS and enable this feature.

    The second option to download the Intel HAXM and x86 Emulator System image is to go directly to the web site: http://software.intel.com/en-us/android and download the necessary components from there.

    2.3. Installation on Linux

    The steps to accelerate the Android emulator for Linux are different than for Windows and Mac OS X as Intel HAXM is not compatible with Linux so you would need to use KVM (kernel-based virtual machine) instead. The steps below were carried out using Ubuntu* 12.04 and may differ slightly with other Linux distributions.

    As with Windows (and Mac OS X), first you need to download the Android SDK from the Android developer site. You will find an ADT (Android Developer Tool) bundle that contains both Eclipse* IDE and the Android SDK. Download the zip file and extract it to your Linux machine. Make sure you choose the right version for your Linux distribution, either 32- or 64-bit. You can check this easily by using the command:

    file /sbin/init

    Before you start installing the packages required for KVM, it is recommended to make sure you have the latest repository, and you can do this by typing:

    sudo apt-get update

    2.3.1. Installation of KVM

    To install and run KVM, which is a full virtualization solution for Linux on x86 hardware (i.e., Intel VT), you first need to check if your CPU supports hardware virtualization, you can do this by typing:

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

    If the result is 0, that means your CPU does not support hardware virtualization, which is necessary to run the KVM. If you get 1 or more, that means you’re good to go, but still make sure it is enabled in your BIOS (see Section 2.2).

    Next, you need to install KVM unless you already have it installed. You can check if your processor supports KVM by typing:

    kvm-ok

    If you have KVM, you will see this:

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

    Otherwise, if you see this, you need to go to BIOS and turn on Intel VT:

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

    The next step is to install the KVM and a few other packages needed. To do so, type

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

    In the next window, you can select No configuration if you want to leave your config unchanged:

    Next, add your user to the KVM group and libvirtd group. To do so, type:

    sudo adduser your_user_name kvm
    sudo adduser your_user_name libvirtd

    After the installation, re-login so that the changes take effect. You can test the installation by typing:

    sudo virsh -c qemu:///system list

    You are now ready to go to the next step, which is creating and running the AVD (Android Virtual Device). This procedure is the same for both Linux and Windows.

    2.4. Creating an AVD (Android* Virtual Device)

    After installing the SDK and Intel HAXM (or KVM with Linux), you can create a virtual device that has hardware-accelerated emulation. To do that, go to the AVD Manager and create a new device. Make sure you select Intel Atom (x86) as the CPU/ABI. The selection appears in the drop-down only if you have the Intel x86 system image installed, for additional graphics smoothness switch on the GPU emulation when creating your AVD.

    Click on New and create your x86 AVD. Make sure you select an API that is supported by an x86 system image, CPU/ABI is set to x86, and you have enabled GPU (OpenGL ES*) emulation. Once you have done that, click on the Create AVD to create the AVD.

    You can launch the x86 AVD by clicking on Start, then Launch.

    If you are successful with the installation, when the emulator is starting, you will get a dialog box showing that Intel HAXM is running in fast virtual mode.

    If you need further convincing that you are using an x86 system image, you can always check the details in the ‘About phone’ within the emulator.

    The performance gain that you’ll see with Intel HAXM or KVM depends on your PC, drive, memory, etc., but should be between 5x to 10x order of magnitude. The screen shot below shows a side-by-side comparison from an x86/HAXM enabled-AVD versus an ARM-based AVD. The x86 AVD booted to the lock screen within 15 seconds whereas the non-Intel AVD took 40 seconds – a big difference.

    [The performance gain that you’ll see with the Intel HAXM (or KVM) should be between 5x to 10x depending on your system configuration: 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. Configuration: Mac Book Pro was used for testing in this case. For more information go tohttp://www.intel.com/performance”]

    3. Best Known methods

    3.1. Testing your application with the emulator from Eclipse

    Whether it’s an NDK-based application or Dalvik* application, you can use Intel HAXM to speed up the emulator where you do testing. If you are developing with Eclipse, you can follow these easy steps to make sure you are using the Intel HAXM when you start the emulator.

    First, make sure you created your AVD as described in step 2. If you have the AVD ready, go to Run As -> Run Config as shown below:

    You should land on a page like this:

    Here, you can select the AVD you want by checking the box. After you have created your AVD and set up your configuration, start compiling your project and debug it with the emulator by selecting Run As -> Android Application. This will automatically start the hardware-accelerated AVD.

    After the AVD has started, you should see the home screen of your application (after unlocking the screen).

    3.2. Submitting multiple APKs for different ABIs vs. submitting fat binaries to Google Play

    In the past, you would submit a fat binary for your developed application, which would contain all of your libraries and NDK file(s), not being able to differentiate between the architectures. That would mean that the users had to download the whole APK containing files that are not relevant to the specific architectures, i.e., x86 users would have ARM code and vice-versa. The downside of this is that if you have a really fat binary, the user was forced to download a big amount of data that would not apply to the device. Typically, this is still acceptable if your APK is under 10 to 20 MB.

    Intel/Google have now implemented a CPU filtering mechanism, meaning you can now submit multiple APKs containing the different libs specific for each architecture by following the suggested versioning code shown below.

    The first digit refers to the ABI, i.e., 6 for x86; then the API level that you target, i.e., 11; the screen size, 13; and then the version number of your application: 3.1.0.

    Make sure that you have at least an 8-digit version number and assign the highest first digit to the x86 version. In the example above, you would put 6 for x86, 2 for ARMv7 and 1 for ARMv5TE. Doing so will make x86 versions preferred on the x86 devices and ARM versions on ARM devices.

    By following these guidelines, you can make sure that your users get the best performance out of the device they own. Furthermore, you may avoid users trying to run applications on specific devices due to code translation problems.

    More info can be found here: http://software.intel.com/en-us/articles/google-play-supports-cpu-architecture-filtering-for-multiple-apk.

    3.3. Compile your NDK for x86

    This section will show you how to compile your application’s NDK part for x86.

    In order for your NDK-based application to run on an x86 AVD, you need to compile your NDK lib for the x86 architecture. To do so, follow these simple steps:

    Open a command prompt and navigate to the folder of your NDK files, like below:

    Make sure you have set the Environment Variable Path so you can use the ndk-build script from anywhere.

    3.3.1. Adding the path of NDK to your Environment Variable

    In order to setup your environment variable for the NDK, you need right-click on Computer, and select Properties. Go to Advanced system settings and find Environment variables. Select Path and click Edit. At the end of the ‘Variable Value’ string, add the path to your root folder of NDK, the one that contains the ndk-build.cmd file as in the image below:

    3.3.2. Compiling with the NDK

    After you have navigated with the command prompt to your NDK folder, execute:

    ndk-build APP_ABI:=all

    This will compile your NDK file for each architecture available, i.e., ARMv5TE, ARMv7, x86, and mips.

    To compile for a specific architecture, replace ‘all’ with the different architectures. For example:

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

    Make sure you refresh your project in Eclipse in order to capture your latest settings, i.e., latest folders created by the ndk-build script. In the Folder libs of your projects, you should now see four folders, one for each of the architectures.

    You are now ready to use the x86 AVD with your NDK application.

    3.3.3. Another way of compiling with the NDK

    Another way of compiling your native code for all the architectures, including x86 is to modify your Application.mk file which you would find in the jni folder. If you do not have an Application.mk file, you can create one yourself and add the instruction below:

    APP_ABI:=armeabi armeabi-v7a x86 mips

    This way, when you run the batch file, i.e., the ndk-build script, it will compile the libraries for all the architectures available.

    Also, for easier use, instead of listing all the architectures, you can just put ‘all’:

    APP_ABI:=all

  • Developers
  • Android*
  • URL
  • Getting started
  • Application Development Hackletics has Ignited

    $
    0
    0

    It is very exciting to be on the verge of helping lead a two week application development. It is something of a perfect storm. We have many Hackletic Poobahs helping. Of course, Paul Steinberg, architect of the Code for Good Hackathons. We also have Brad Hill, an Intel HTML5 expert who has helped run each hackathon. We have six of my students, all involved with past hackathons.

    It is going to be interesting to spread the contiguous hackathon hours over a two week period and help new students create a working app.

    In case you might like to follow along from home, below are resources we advocate. More good stuff to follow.

    http://www.html5rocks.com
    • Oriented for mobile, gaming, and business developers
    • Leads to boatloads of other resources
    • Resource lists tailored to dpecific HTML5 features
    http://www.w3schools.com
    • Tutorials, Examples, and Quizzes, oh my!
    • HTML5, CSS, CSS3, JavaScript, jQuery, SQL, php, and XML
    • Good drill down on the above stuff
    http://www.impressivewebs.com
    • Design and design issues
    • Exemplary web sites
    • Loves CSS
    http://www.romancortes.com/ficheros/css-coke.html
    • Even if you don't like coke
    • Pretty good effect
    http://toolbox-appdeveloper.intel.com/html5playground/
    • Intel's HTML5 Playground
    • Put HTML5 in upper window, results shows immediately in lower window
    • I used it to prepare this post
    http://codepen.io/
    • Like Intel's HTML5 playground
    • Allows complex HTML, CSS, and JavaScript codes
    • Really cool tags page provides examples tied to a specific tag
    Students are involved in an ideation process this week with master entrepeneur, Henrik Scheel. It will be delightful to see the carefully thought out strategies and solutions that await us. 

    Life is good.

    Icon Image: 

    Wakelocks: Detect No-Sleep Issues in Android* Applications

    $
    0
    0

    Abstract

    Android* applications may increase battery consumption significantly if they use wakelocks improperly. In this document, we will give some hints and tips on how to identify No Sleep bugs related to wakelock misuse.

    1. Introduction
    2. Wakelock
    2.1. What is it?
    2.2. Android User Wakelocks
    2.3. Android Kernel Wakelocks
    2.4. No-Sleep bugs
    3. Identifying No Sleep ugs
    3.1. Using adb
    3.2. Using BetterBatteryStats application
    4. Test case
    5. Conclusion
    6. Reference

    1. Introduction

    Limiting battery power consumption is essential for smartphones. To get the best autonomy possible, Android OS is designed to opportunistically go into sleep mode as soon as it detects no user activity on the system. Some applications require the device to stay on even if there is no user interaction for a long time. Examples of this are watching a video, listening to music, using GPS, and playing a game. Android provides such a mechanism for the OS or applications in order to keep the device awake. This mechanism is called a wakelock. For more details, please read Christopher Bird’s article: “Wakelocks for Android”.

    The introduction of such a mechanism puts the responsibility of managing the component’s activities on the application developer. If used incorrectly, the application can drain the battery significantly even when the application is not running in the foreground.

    2. Wakelock

    2.1. What is it?

    A wakelock is a software mechanism to control the power state of the host device. The OS exports explicit power management handles and APIs to specify when a particular component needs to stay on, or awake, until it is explicitly released from duty.

    The wakelock mechanism is implemented in two levels: user and kernel. The figure shows the internal design of Android wakelock implementation. The user wakelock can be utilized by either high-level OS services or applications and is provided by the power management service. It allows an application to control the power state of the device. A kernel wakelock is held by the OS kernel or a driver. A user wakelock is mapped to a kernel wakelock. Any active kernel-level wakelock prevents the system from being suspended to ACPI S3 (suspended to RAM) state, which is the highest power saving state for mobile devices.

    2.2. Android User Wakelocks

    The Android framework exports the wakelock mechanism through the PowerManager.Wakelock class and identifies four types of user wakelocks:

    Flag ValueCPUScreenKeyboard

    PARTIAL_WAKE_LOCK

    On

    Off

    Off

    SCREEN_DIM_WAKE_LOCK

    On

    Dim

    Off

    SCREEN_BRIGHT_WAKE_LOCK

    On

    Bright

    Off

    FULL_WAKE_LOCK

    On

    Bright

    Bright

    Note that since API level 17, FULL_WAKE_LOCK has been deprecated. Applications should use FLAG_KEEP_SCREEN_ON.

    Wakelocks can be acquired to force some of the components (CPU, screen, and keyboard) to stay awake.

    Use special caution with the PARTIAL_WAKE_LOCK as the CPU will continue to run regardless of any display timeouts or the state of the screen and even if the user presses the power button. This may lead to silent power drain as the phone looks like it is in standby mode (screen is off), but is actually fully awake.

    In all other wakelocks, the user can still put the device to sleep using the power button. All wakelocks, except partial wakelocks, will be implicitly released after the power button is pressed.

    This is how applications can hold a wakelock. It is basically an Acquire/Release mechanism. The application acquires a wakelock when it needs some components to stay on. When those are not needed anymore, the wakelock needs to be released.

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
    wl.acquire();
    ..screen will stay on during this section..
    wl.release();

    2.3. Android Kernel Wakelocks

    Kernel wakelocks are low-level wakelocks held by the kernel. They can be acquired/ released internally from the kernel. As such, application developers have less direct control on them, but an application’s behaviour can indirectly trigger these wakelocks and increase battery consumption inadvertently.

    Here are examples of kernel wakelocks.

    Wlan_rx: Held by the kernel when data is sent or received over Wi-Fi*.

    PowerManagerService: Is the container for all partial wakelocks.

    Sync: Held while the sync process is running.

    Alarm_rtc: Handles the alarm (when an application or process checks periodically on something).

    Main: Keeps the kernel awake. This is the last one to be released when the system goes to suspend mode.

    2.4. No-Sleep bugs

    The application has to release every wakelock it acquires at some point to allow the system to go back to a deep sleep mode. This acquire/release mechanism may lead to some bugs if the wakelock is never released. A wakelock remains held even if the application holding it is not running in the foreground anymore. A wakelock is released when it is explicitly released by a release call or if the application is actually killed (force close). Leaving some wakelocks held prevents the system from going into deep sleep mode even if there is no activity, significantly increasing the power drain and silently reducing the battery autonomy. This is called a No-Sleep bug. Due to the event-driven nature of Android, developers may not think of all the code paths that their applications had acquired wakelocks and, therefore, need to close. This type of bug is called a No-Sleep bug code path.

    Another occurrence of this type of bug is when the release happens before the wakelock has been effectively acquired. This can happen in multithreaded code where the acquisition and release of the wakelock happen in different threads. This is called a No-Sleep bug race condition.

    The last issue is the No-sleep dilation, where the wakelock is acquired longer than what is actually necessary.

    Why are these issues important to look at? According to a study made by P. Vekris: “55% of 328 applications using wakelocks do not follow our policies for no-sleep bugs” [2012]. Some major applications have been released with No-Sleep bugs. So developers need to be aware of this specific point in order for their applications to run optimally.

    3. Identifying No Sleep bugs

    The no sleep bug can be tackled in two ways: either a static analysis doing a code path scanning or dynamically at run time. In this paper we will focus on run-time analysis.

    This method does not guarantee you’ll find all the wakelocks bugs in an application. It will however help you spot some wakelock issues if they occur during run time. To identify a wakelock issue, you need to follow a code path where the wakelock is not released. Testing an application against no sleep bugs involves manipulating the application, trying different ways to exit it, at different places in the application to see if a wakelock persists.

    In some cases, it may be necessary to prevent the system from going into deep sleep even if the application is not in the foreground anymore. An application may need to perform a task in the background. This is the case, for example, if the application has to perform a long download: a video or game dataset. The application may be put in the background by the user while it’s downloading, but the phone should stay awake until the download is completed. In that case, the application may hold a wakelock until the download is completed. Of course, you should check that the wakelock is released at some point. For example, if the phone loses network connection in the middle of a download, the phone should not remain awake if the action cannot be performed anymore.

    In summary, identifying a No Sleep bug is very context dependent. There is no predefined criterion that allows someone to easily identify this issue. Only common sense can assess these types of bugs.

    3.1. Using adb

    The simplest tools to look at wakelocks are shell commands.

    To get a full picture of the kernel wakelocks, type:

    adb shell cat /proc/wakelocks

    namecountexpire_countwake_countactive_sincetotal_time
    "PowerManagerService"1502000337817677431
    "main"15000984265842688
    "alarm"151207920217778251643
    "radio-interface"1600016676538930
    "alarm_rtc"8044001204136324759
    "gps-lock"100010753659786
    namesleep_timemax_timelast_change
    "PowerManagerService"957294091221409216636679723417252748
    "main"02124247323559498127170228
    "alarm"2176173620473579769419723371461242
    "radio-interface"016593284969486387144974
    "alarm_rtc"1200253446201660829365019483176054624
    "gps-lock"01075365978637632803440

    For images using kernel 3.4 or higher, use “adb shell cat /sys/kernel/debug/wakeup_sources.” Even though it gives all the information, this format is not very user friendly. The tools we are introducing below are much handier.

    A simple way to check a specific application is by using “adb shell dumpsys power.” Below is a typical output of this command. You can see in red the user wakelocks present at the time the command was issued. This command gives a snapshot of the user wakelocks present in the system.

    Power Manager State:
    mIsPowered=true mPowerState=3 mScreenOffTime=1618305 ms
    mPartialCount=3
    mWakeLockState=SCREEN_ON_BIT
    mUserState=SCREEN_BRIGHT_BIT SCREEN_ON_BIT
    mPowerState=SCREEN_BRIGHT_BIT SCREEN_ON_BIT
    mLocks.gather=SCREEN_ON_BIT
    mNextTimeout=2382037 now=2378097 3s from now
    mDimScreen=true mStayOnConditions=3 mPreparingForScreenOn=false mSkippedScreenOn=false
    mScreenOffReason=0 mUserState=3
    mBroadcastQueue={-1,-1,-1}
    mBroadcastWhy={0,0,0}
    mPokey=0 mPokeAwakeonSet=false
    mKeyboardVisible=false mUserActivityAllowed=true
    mKeylightDelay=6000 mDimDelay=587000 mScreenOffDelay=7000
    mPreventScreenOn=false mScreenBrightnessOverride=-1 mButtonBrightnessOverride=-1
    mScreenOffTimeoutSetting=600000 mMaximumScreenOffTimeout=2147483647
    mLastScreenOnTime=27380
    mBroadcastWakeLock=UnsynchronizedWakeLock(mFlags=0x1 mCount=0 mHeld=false)
    mStayOnWhilePluggedInScreenDimLock=UnsynchronizedWakeLock(mFlags=0x6 mCount=0 mHeld=true)
    mStayOnWhilePluggedInPartialLock=UnsynchronizedWakeLock(mFlags=0x1 mCount=0 mHeld=true)
    mPreventScreenOnPartialLock=UnsynchronizedWakeLock(mFlags=0x1 mCount=0 mHeld=false)
    mProximityPartialLock=UnsynchronizedWakeLock(mFlags=0x1 mCount=0 mHeld=false)
    mProximityWakeLockCount=0
    mProximitySensorEnabled=false
    mProximitySensorActive=false
    mProximityPendingValue=-1
    mLastProximityEventTime=0
    mLightSensorEnabled=true mLightSensorAdjustSetting=0.0
    mLightSensorValue=11.0 mLightSensorPendingValue=10.0
    mHighestLightSensorValue=47 mWaitingForFirstLightSensor=false
    mLightSensorPendingDecrease=false mLightSensorPendingIncrease=false
    mLightSensorScreenBrightness=42 mLightSensorButtonBrightness=0 mLightSensorKeyboardBrightness=0
    mUseSoftwareAutoBrightness=true
    mAutoBrightessEnabled=true
    creenBrightnessAnimator:
    animating: start:42, end:42, duration:480, current:42
    startSensorValue:47 endSensorValue:11
    startTimeMillis:2361638 now:2378092
    currentMask:SCREEN_BRIGHT_BIT
    mLocks.size=4:
    SCREEN_DIM_WAKE_LOCK          'StayOnWhilePluggedIn_Screen_Dim' activated (minState=1, uid=1000, pid=388)
    PARTIAL_WAKE_LOCK             'StayOnWhilePluggedIn_Partial' activated (minState=0, uid=1000, pid=388)
    PARTIAL_WAKE_LOCK             'HDA_PARTIAL_WAKE_LOCK' activated (minState=0, uid=10046, pid=4690)
    PARTIAL_WAKE_LOCK             'AudioOut_2' activated (minState=0, uid=1013, pid=157)
    mPokeLocks.size=0:

    To identify if any wakelocks still held after an application has been put in background, you can follow this process:

    1. Connect the device to USB.
    2. Launch the application and play with it.
    3. Press the power button to go to sleep mode or exit the application in some way.
    4. Wait for about 20 sec.
    5. Type the following instruction in command line:
    > adb shell dumpsys power
    6. Check if there are any PARTIAL_WAKE_LOCKs like this one for example:
    PARTIAL_WAKE_LOCK       ‘AudioOut_2’ activated(minState=0, uid=1013, pid=157)
    7.Repeat step 5 every 15 sec 3 to 5 times. If the result stays the same, there may be an issue.

    3.2. Using BetterBatteryStats application

    BetterBatteryStats* (https://play.google.com/store/apps/details?id=com.asksven.betterbatterystats&hl=en) is an Android app by Sven Knispel that you can buy on Google Play. It collects information that allows you to spot battery drain, especially wakelock issues.

    First, by selecting the ‘Other’ entry, you can check the deep sleep and awake modes versus the total time. Ideally, most of the time, the phone should be in Deep Sleep if it is not in use.

    You can also compare the Awake time vs. the Screen On time to see when there is actual activity. Under normal conditions, the Screen On time and the Awake time should be close.

    You can check the battery charge evolution and the awake, Screen On, and Wi-Fi* states over time.

    Then you can check the kernel wakelocks. You can check the time spent within each kernel wakelock type as well as the count. High time or high counts may be symptomatic of a problem. From this report you cannot link a hotspot to a specific application or process but you can spot a specific behaviour that may be triggered by a specific application.

    In the Kernel Wakelock report, the line “PowerManagerService” aggregates the time spent in user wakelocks. If this line shows a hot spot, you can drill down by checking the Partial Wakelock report.

    Most of the time, the partial wakelock refers to the application that holds it. It’s a great help to find the culprit. Though some times, some activities may be launched by other apps. For example, a game may play sound through the AudioOut channel assigned to the Android Media gallery. If not coded properly, it would be the game’s fault for not closing the sound channel. It is never the Android Gallery’s fault.

    The AlarmManager may signal that wake ups were caused by alarms or that an application has made numerous alarm modifications. You may want to check the Alarm section but it will only work if you have a rooted image.

    Network entry is also accessible only on rooted images. It can be useful if you suspect some high traffic on the network. The multipdp/svnet-dormancy kernel wakelock may indicate that you also have some high network usage.

    4. Test case

    Let’s consider a real case using a game. Start it and play for about five minutes, and then exit the game in an unusual way. In our case we forced the exit by pressing the Home button. The music stopped, and the home screen displayed. From a user standpoint, everything looks fine. After a few minutes of inactivity the screen goes dark as expected. Let’s leave the phone in this state for about half an hour and then check it with BestBatteryStats. On the “Other” screen, you can see that the phone remained awake despite the fact the screen was not on. You can also see that the battery depletion rate is at 8.5%/hr. So in this state, the phone with a full battery will last no more than 12 hrs.

    Now let’s look at the Kernel wakelocks. We can see that two kernel wakelocks remain despite the fact that there is no activity. One is the PowerManagerService, which means that there is a user partial wakelock, and the other is an AudioOutLock wait lock. Let’s have a look at the Partial wakelock screen.

    Looking at the partial wakelock screen, we can see that an audio channel is still open with the media gallery application. This is curious as the media gallery application was not used explicitly by the user. The game actually launched the Media Gallery for the game’s music playback. The developer has simply forgotten to close the audio channel when the application is interrupted by the home button. The developer needs to take this case into consideration and modify the application accordingly.

    5. Conclusion

    Wakelocks are very useful and powerful tools. But if misused, they can have a very negative effect on the device battery life, considerably impacting the user experience. It is important for developers to check during QA that their code is not causing any No Sleep bugs. They should consider using the available tools to analyse the battery impact of their application in real life usage and try to limit their impact on the customer device as much as possible.

    6. Reference

  • Developers
  • Android*
  • Android*
  • URL

  • Intel® NFC-Hunt Prize draw

    $
    0
    0

    Congratulations YOU found the Intel® NFC hunt prize draw.

    Fill in the correct answers below and you will get further information how to enter the competition to win one of our Orange* Smartphones with an Intel Inside®.

    The actual Prize draw will take place on Wednesday, June 19th at 18:00h ( 6PM) at the Intel booth.

    You need to be present to win. See you all there!

    How many smartphones are there currently available in Europe?

     2
     4
     6
     8

    In which countries was the Orange* Intel® powered phone launched?

     Spain & France
     France & UK
     Germany & Italy

    Which game comes preloaded on the Orange* smartphone?

     Uno*
     Need for Speed*
     Candy Crush Saga*

    What is the name of Intel's web based resource for software developers?

     Intel® Developer Zone
     Intel AppUp® Program
     Intel Software

    Terms and Conditions apply. Please ask a member of staff! Copyright ©Intel Corporation. All rights reserved. Intel Corporation, 2200 Mission College Blvd., Santa Clara, CA 95052-8119, USA. *Other names and brands may be claimed as the property of others.
  • Android Event Blog
  • Icon Image: 

  • Event
  • Case Study: How to Enable Intel® C++ Compiler for Android Application Development - What’s Behind the Scene

    $
    0
    0

    About the Author

    Zhen is an application engineer with Intel Software and Service group focusing on Android applications development and optimization for x86 devices, Web HTML5 application development. Besides, Zhen also has rich experience in mobile application performance tuning and power optimization.

    Introduction

    Everimaging HaoZhaoPian( Good Photo) is a versatile image processing application. It provides a whole new level of processing experience with High-dynamic-range (HDR) images, Edit, Manage, Share, and other powerful functions.

    The team chose to use the Intel® C++ Compiler to recompile the HDR function (Native Development Kit) of this app. The HDR algorithm contains three main modules: OpenCV, merging, and tone mapping. Here, OpenCV and merging were recompiled by Intel® C++ Compiler and the performance was improved up to 300%1.

    This document describes:

    • Why the performance improved so much
    • What is the hotspot in this app and what is the right way to do Intel® C++ Compiler optimization.
    • How does it help application developers get the most benefit with Intel® C++ Compiler

    Benchmark on HaoZhaoPian

    The next table shows the performance results of running the Merging module of the HaoZhaoPian HDR app after compiling with Intel® C++ Compiler.

    Feature: HDR Merging Process

    Photo Size: 2048x1536


    1 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. Configuration(s): [describe config + what test used + who did testing]. For more information go to http://www.intel.com/performance

    Figure 1. [Intel® C++ Compiler improved performance on Intel® Medfield* Platform by more than 200 percent compared to the typical benchmark (with less than 35 percent).]

    You may be asking “why?” The next sections will tell you.

    HaoZhaoPian Optimization Benchmark Overview

    Benchmark testing is focused the two main parts of HDR processing: thumbnail merging and completed photo processing/storage. We ran the software on several platforms (Intel® Architecture version APP on our PR3, ARM version APP on ARM phone, Apple version APP on iPhone with the same or similar release version number) and recorded the total time.

    We considered several possibilities for the performance improvement. The original version of OpenCV compiled with GCC may have some obscure compatible bugs on Intel® Architecture, but Intel® C++ Compiler avoid it.

    Automatic vectorization plays a leading role here because the alignment algorithm (the main hot spot of HDR) in OpenCV benefits a lot from automatic vectorization.

    Hotspots of the Key Algorithm

    Figure 2. Hotspots in HaoZhaoPian on Intel® Architecture Form Factor Reference Design

    Figure 3. Hotspots in HaoZhaoPian on Samsung Galaxy S3*

    Two Hotspots in HaoZhaoPian That Benefitted from Intel® C++ Compiler

    The first was hmMergeN, a side hotspot. Its performance improved 2x. This module, developed by Everimaging, was designed to merge the different elements in HDR processing. It is hard to trace the source code, because the core algorithm in this function belongs to Everimaging and we cannot parse what it you want.

    The second was hmAlign, a main hotspot. Its performance improved 7x.2 hmAlign uses the picture align algorithm in OpenCV to align two photos shot in HDR mode. It can be traced deeply since OpenCV is an open source program initiated by Intel. The next section is based on this one.


    2 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. Configuration(s): [describe config + what test used + who did testing]. For more information go to http://www.intel.com/performance

    Analyze on the key hotspots of OpenCV

    Our OpenCV test environment included the following:

    • Software Development Platform: Tablet DV2.1
    • Android version: 4.0.4
    • Test Application: HelloOpenCV_gcc; HelloOpenCV_icc
    • Main Function: Abstract the features of SURF and calculate the total number of SURF features.
    • Dependent Library: libopencv.so (ICC version and GCC version)

    The include files we used are listed below.

    The code for the Main Function is shown below.

    We obtained the following test results:

    After trying a variety of functions in OpenCV, we finally found the key function that benefitted the most from re-compiling with Intel® C++ Compilerusing default parameters. It was the cvExtractSURF() function.

    What is cvExtractSURF()?

    [Put a lead in sentence here.]

    The cvExtractSURF function extracts the most robust features from an image. For each feature it returns its location, size, orientation, and optionally the basic or extended descriptor.

    What does cvExtractSURF() do?

    The cvExtractSURF() function can be used for object tracking and localization, image stitching, etc. As the following code snippets show, [say why this code is here]

    Using Vtune™ Analyzer to Chart and Some Other Tips

    These screen shots show tracing the hotspot of libOpenCV-GCC use the Vtune Analyzer.

    These screen shots show tracing the hotspot of libOpenCV-ICC use the Vtune Analyzer. [Tell the what the screen shots show. What are they looking at and why?]

    What is Intel® Threading Building Blocks (Intel® TBB)?

    Intel® Threading Building Blocks (Intel® TBB) is a C++ template library that Intel developed for writing software programs that take advantage of multi-core processors.

    What is the Intel® Math Kernel Library (Intel® MKL)?

    The Intel® Math Kernel Library (Intel® MKL) is a library of optimized math routines for science, engineering, and financial applications. It includes the following [put what these things are]:

    • BLAS
    • LAPACK
    • ScaLAPACK
    • sparse solvers
    • fast Fourier transforms
    • vector math

    The next screen shot, logged by vTune, shows the CPU time consumed to run the GCC version APP.

    The next screen shot shows the CPU time consumed to run the ICC version.

    Issues when Using GCC to Compile OpenCV

    We think using GCC produced these issues:

    • OpenMP is removed in Intel® C/C++ Compiler XE 12.1 for Linux*. OpenCV (v2.0) no longer uses OpenMP.
    • Intel TBB does NOT take effect when using the default GCC compiling setting.
    • Compared to Intel MKL, libm.so, the math library, takes lots of extra time on Inter-Process Communication.

    Summary

    The next two graphs produced in [what tool?] show the performance differences using GCC and Intel® C++ Compiler to compile OpenCV.

    OpenCV compiled by GCCVSOpenCV compiled by ICC

    Different Ways to Solve This Issue – Intel TBB

    Use Intel TBB to enable parallel code in OpenCV. OpenMP is no longer used. Important note: Only Intel TBB 2.2 or later will work. If TBB is installed (using it is optional), turn it on using the WITH_TBB option and adjust the Intel TBB include and library paths if needed. You should see the following message in the CMake output:

    USE TBB: YES

    Other Ways to Solve This Issue - Intel® Integrated Performance Primitives(IPP)

    OpenCV does not require IPP, but can be configured to use IPP to make color conversion, Haar training and DFT functions run faster. Using IPP (Optional). If you have IPP installed on your machine and want to build OpenCV with IPP support, check if IPP is turned on in CMake configuration options and if it was detected.

    Further Research

    We hope to have time to answer these questions:

    • Why does libm take such a long time to do these jobs? Low performance on IPC does not seem to be the only reason.
    • Compared to libm, why is Intel MKL so efficient?
    • Why does the ARM version have less impact on this issue?
    • Are there other performance-critical cases like OpenCV that depend on multi-thread or math algorithm library that we can help?

    Optimized Intel® C++ Compiler Parameters for X86 NDK Applications

    Optimize x86 NDK applications

    Compiler flags

    To use compiler flags in the ndk-build script, add the following line to the jni/Android.mk file:

    LOCAL_CFLAGS    := #add here the compiler flags

    Be sure to benchmark if the particular flags are really improving performance!

    Compiler flags GCC

    So the suggested flags for good performance would be: - O3 -ffast-math -mtune=atom -msse3 -mfpmath=sse

    Intel® C/C++ Compiler XE 12.1 for Linux*

    Based on the high performance Intel® C/C++ Compiler XE 12.1 for Linux*, widely used by HPC customers for achieving better performance on Intel® architecture Intel® C/C++ Compiler XE 12.1 for Linux* comes with a well established support infrastructure.

    Intel® C++ Compiler for Android can be used for nearly all Android components. It integrates seamlessly into AOSP and can be used with NDK projects and standalone tool-chain.

    SIMD Instruction Enhancements, especially on Intel® Atom™ processor

    Intel® C++ Compiler Optimizations Specific for the Intel® Atom™ Processor

    Use the –xSSSE3_ATOM optimization switch. And the optimizations include: Streaming SIMD Extensions 3 (SSE3) instruction support; Use of LEA for stack operations for instruction reordering; Support for movbe instruction (-minstruction=movbe).

    What you should know about Inter Procedural Optimizations (IPO)

    IPO include: O2 and O3 activate “almost” file-local IPO (-ip); Extending compilation time and memory usage; Working for libraries; In-lining of functions is most important feature of IPO but there is much more

    Extends optimizations across file boundaries

    Automatic Vectorization

    Vectorization use SIMD instructions (single instruction, multiple data). The options of Vetorization are “-vec: enabled by default with O2/3” and “-vec-report[n]”. A variety of auto-vectorizing hints and user-mandated pragmas that can help the compiler to generate effective vector instructions.

    Optimize x86 NDK applications

    For good performance use the following compiler flags in Intel® C++ Compiler.

    Package the Intel Libraries with Your Application

    The Android build system can include third-party libraries in the final apk files. Be sure to copy the Intel Compiler libraries libintlc.so, libimf.so, libsvml.so in your jni folder. Add the following code to your Android.mk file in the jni folder:

    include $(CLEAR_VARS)
    LOCAL_MODULE    := libintlc
    LOCAL_SRC_FILES := libintlc.so
    include $(PREBUILT_SHARED_LIBRARY)
    include $(CLEAR_VARS)
    LOCAL_MODULE    := libimf
    LOCAL_SRC_FILES := libimf.so
    include $(PREBUILT_SHARED_LIBRARY)
    include $(CLEAR_VARS)
    LOCAL_MODULE    := libsvml
    LOCAL_SRC_FILES := libsvml.so
    include $(PREBUILT_SHARED_LIBRARY)
    include $(CLEAR_VARS)
    LOCAL_MODULE    := libirc
    LOCAL_SRC_FILES := libirc.so
    include $(PREBUILT_SHARED_LIBRARY)

    Then load the Intel compiler libraries from Java* code. This needs to be done manually because only libraries from the system lib folder are loaded automatically. The application library needs to be loaded after the Intel compiler libraries.

    System.loadLibrary("intlc");
    System.loadLibrary("imf");         // libimf.so depends on libintlc.so! Must put after libintlc.so!
    System.loadLibrary("svml");        // libsvml.so depends on libintlc.so! Must put after libintlc.so!
    System.loadLibrary("irc");        // libirc.so depends on libintlc.so! Must put after libintlc.so!

    System.loadLibrary("hello-jni");   // replace with your application library name

  • Developers
  • Android*
  • Android*
  • URL
  • Beacon Mountain for Android*: novo ambiente gratuito de desenvolvimento de Apps Android*

    $
    0
    0

    A Intel anunciou durante o Google I/O 2013 o lançamento de um novo ambiente completo para desenvolvimento de aplicações para Android (Atom™ e ARM*), o Beacon Mountain for Android*.

    As principais funcionalidades desta versão da ferramenta são:

    • Instalação de ferramentas de terceiros comumente utilizadas, junto com ferramentas da Intel para criar um ambiente de desenvolvimento no sistema host para a criação de aplicativos Android*
    • O Beacon Mountain instala tudo o que um desenvolvedor precisa com poucos cliques, permitindo que o desenvolvedor começe a criar seus apps com maior rapidez
    • Suporta o Windows 7 e 8, e o suporte ao OS X está planejado para o final de junho

    Para ler o anúncio completo do lançamento, clique aqui e assista ao vídeo abaixo para ter uma visão geral do que o novo ambiente pode fazer.


    Icon Image: 

    Android SDK4.0.3 及以上版本支持 Intel x86 模拟器

    $
    0
    0

    现在 Android SDK 终于有了 Intel x86 上的模拟器了, 现在在 sdk manager 上可以下载相应的模拟器映像:

    下载安装完之后就可以在虚拟机选项中选择cpu为intel x86:

     实际运行比arm模拟器快太多了,毕竟是原生支持,现在在没有手机的情况下终于可以直接用模拟器来调试程序了:

  • Curated Home
  • Icon Image: 

  • News
  • Beacon Mountain: A Development Environment for Android Apps

    $
    0
    0
    English
    Beacon Mountain: A Development Environment for Android Apps

    Learn about Beacon Mountain - Intel's development environment for creating applications for Intel Atom and ARM*-based devices running Android* operating systems. Beacon Mountain installs common third-party tools in a few clicks, allowing the developer to start creating faster. This initial release supports Windows 7 and 8 64-bit host systems.

    For more information link

  • Tutorial
  • Developers
  • Android*
  • Microsoft Windows* 8
  • Android*
  • Windows*
  • Android* Development Tools
  • Intel Hardware Accelerated Execution Manager (HAXM)
  • Tutorial Operating System
  • android
  • microsoft windows
  • Microsoft Windows 8
  • game development
  • debugging
  • Development Tools
  • graphics
  • optimization
  • power efficiency
  • threading
  • GameSDK
  • framerate
  • Intel Integrated Performance Primitives
  • intel threading building blocks
  • Intel Graphics Performance Analyzers
  • Intel Hardware Accelerated Execution Manager
  • Рекомендации по установке образа Intel® Atom x86 для Android* Jelly Bean 4.2

    $
    0
    0

    Введение

    Эти рекомендации помогут вам установить образ Intel® Atom x86 для Android* Jelly Bean, что может пригодиться при разработке на платформе Intel x86.

    Предварительные требования

    Чтобы установить образ для эмулятора Android x86, требуется пакет Android SDK. Инструкции по установке и настройке пакета Android SDK см. на сайте для разработчиков Android (http://developer.android.com/sdk/).

    Замечание: Для ускорения образа x86 для Android можно использовать Intel Hardware Accelerated Execution Manager (HAXM). Дополнительные сведения см. в разделе "Оптимизация"в этом документе.

    Известные проблемы:

    • Неполадки камеры: сбой камеры при записи видео в системном образе Android 4.2. Эта проблема описана в следующих статьях: http://code.google.com/p/android/issues/detail?id=41227
    • Неполадки браузера: на компьютерах с 32-разрядной Windows Vista браузер вызывает произвольные аварийные сбои эмулятора. Эта проблема описана в следующих статьях: http://code.google.com/p/android/issues/detail?id=42733
    • Неполадки стабильности: возможен аварийный сбой эмулятора, если значение ОЗУ устройства в AVD равно 1024. В настоящее время Intel ведет дополнительное изучение этой неполадки.

    Установка

    Загрузка с помощью Android SDK Manager

    1. Запустите Android SDK Manager.
    2. В разделе Android 4.2 (API 17) выберите Intel x86 Atom System Image:

    3. Затем нажмите кнопку Install Package.
    4. Прочитайте лицензионное соглашение с корпорацией Intel. Если вы принимаете условия соглашения, выберите Accept и нажмите кнопку Install.
    5. Диспетчер SDK Manager загрузит и извлечет системный образ в нужное расположение в папке Android SDK.

    Использование системного образа

    1. Запустите Android AVD Manager и создайте новое виртуальное устройство AVD, выбрав для параметра Target значение Android 4.2 – API Level 17, а для параметра CPU/ABI — значение Intel Atom (x86).

      Образ Intel Atom x86 для Android Jelly Bean может использовать аппаратные возможности графического процессора (GPU) для повышения производительности в играх, программах с высокой графической нагрузкой и при обработке элементов пользовательского интерфейса. Для наивысшей производительности установите флажок Use Host GPU при создании образа.

      Примечание:Функциональность и производительность GPU зависит от установленного в компьютере видеоадаптера и графических драйверов. Ускорение GPU необходимо включать для каждого AVD.

      Примечание:Если значение Intel Atom (x86) параметра CPU/ABI недоступно, проверьте правильность установки системного образа.

    2. Нажмите кнопку Create AVD.
    3. Виртуальное устройство AVD успешно создано и готово к использованию:

    Оптимизация

    Ускорение CPU

    Производительность образа Intel Atom x86 для Android Jelly Bean можно повысить с помощью аппаратной виртуализации на основе технологии Intel VT-x.

    Если на вашем компьютере установлен процессор Intel с поддержкой VT-x, рекомендуется использовать Intel Hardware Acceleration Execution Manager (HAXM) вместе с этим системным образом. Дополнительные сведения о Intel HAXM см. по адресу http://www.intel.com/software/android.

    Примечание:Решение Intel HAXM поддерживает только операционные системы Windows и OS X. Для серверов на базе Linux повышения производительности эмуляторы можно обеспечить с помощью виртуальной машины на базе ядра (KVM). Сведения об установке и настройке KVM в ОС Ubuntu см. в этом руководстве: https://help.ubuntu.com/community/KVM/Installation

    Copyright (C) 2013 Intel Corporation. All rights reserved.
    Intel, Atom, and the Intel logo are trademarks of Intel Corporation in the U.S. and/or other countries.
    All products, computer systems, dates, and figures specified are preliminary based on current expectations, and are subject to change without notice.
    * Другие имена и торговые марки могут быть собственностью третьих лиц.

  • Developers
  • Android*
  • Android*
  • Android* Development Tools
  • Intel Hardware Accelerated Execution Manager (HAXM)
  • Intel® Atom™ Processors
  • Phone
  • URL
  • Реализация сенсорного интерфейса в новых и существующих играх

    $
    0
    0

    Распространение устройств Android* открыло новую эру в области разработки игр: в игры стало возможным привнести «волшебство» сенсорного управления, но при этом создателям игр пришлось столкнуться с целым рядом новых проблем. Во всей истории видеоигр разработчикам приходилось адаптировать свои игры для мышей, клавиатур, джойстиков, других игровых контроллеров. Сенсорные экраны — это еще один интерфейс управления, реализация которого сопряжена с дополнительными затратами на разработку и контроль качества, особенно для существующих игр. Далее мы рассмотрим некоторые часто встречающиеся проблемы и возможные способы их решения.

    Основы сенсорного управления

    Начиная работу в этой области, важно оценить, какими преимуществами обладает данный интерфейс, и как наиболее эффективно использовать эти преимущества. Некоторые игры проще приспособить к сенсорному управлению, другие — сложнее, но даже в самых сложных играх, плохо пригодных для сенсорного управления, адаптация может быть проведена как удачно, так и неудачно. Итак, если оставить за кадром огромную рыночную долю устройств Android с сенсорным экраном, в чем заключается преимущество использования таких устройств?

    Самая простая иллюстрация: представьте себе, с каким удовольствием ребенок рисует пальцами. Все люди с детства привычны к сенсорному управлению: на интуитивном уровне все дотрагиваются до предметов, передвигают их пальцами. Мы видим, как интерфейс меняется в результате наших действий и реагирует на них. Мы можем мгновенно зафиксировать взаимосвязь между нашими действиями и результатом на экране. Иллюзия тактильной обратной связи — это важное преимущество касания. Любая игра с самого начала должна дать пользователям привыкнуть к новым ощущениям, ощутить интуитивное чувство движения, оценить достоинства реакции механики интерфейса. Правильно созданный сенсорный интерфейс сам по себе может стать увлекательной игрой или важным ее компонентом.

    Механика интерфейса должна быть привычной, естественной и плавной. При этом важно добиться достаточно высокой частоты кадров; более простой, но быстро реагирующий на действия пользователя интерфейс предпочтительнее, чем очень красивый, но запаздывающий интерфейс. Без сенсорного экрана интерфейс меню с частотой 15 кадров в секунду не менее удобен, чем при частоте 30 кадров в секунду. Но при использовании сенсорного экрана низкая частота кадров делает работу с интерфейсом психологически некомфортной, особенно при прокрутке и движениях, где требуется плавность. Кроме того, на большинстве устройств со снижением частоты кадров снижается и способность записывать касания сенсорного экрана, что приводит к ошибкам ввода и дополнительно раздражает пользователей. Но даже и без этого достаточно одного лишь психологического эффекта, чтобы отвратить пользователей от такого интерфейса; недостаточно плавный интерфейс может не сильно отставать по фактическому удобству использования, но привлекательностьсенсорного интерфейса будет существенно ниже. Это недостаток интуитивного принципа работы с сенсорными экранами: пользователь не только сразу же ожидает определенной реакции интерфейса, но и раздражается, если его ожидания не оправдываются.

    На практике, при разработке игр непросто гарантировать определенную частоту кадров, тем более что производительность различных устройств Android может существенно различаться. Для настройки графических параметров игры в соответствии с производительностью устройства можно использовать определение семейства набора микросхем при первом запуске игры. Также можно упростить области интерфейса, в которых часто используется сенсорная прокрутка и аналогичные действия. Например, если заменить трехмерный, обновляемый в реальном времени фон меню на высококачественный снимок экрана, интерфейс будет работать значительно быстрее без существенного снижения наглядного качества.

    Основы проектирования

    При проектировании интерфейсов следует учитывать не только общие принципы психологии пользователей, но и целый ряд более конкретных вопросов. В частности, в каких именно местах пользователь будет касаться экрана, и каким образом будут использоваться эти точки касания? Сколько пальцев одновременно будет использовать игрок? Использовать более двух касаний одновременно нежелательно, если предполагается, что пользователь в ходе игры будет удерживать устройство в руках. В некоторых играх, когда два пользователя играют с одним и тем же планшетом, может потребоваться обработка множества точек касания одновременно, а многие наиболее мощные устройства поддерживают десять или более точек одновременного касания. Тем не менее, некоторые устройства с мультисенсорным вводом поддерживают касание лишь в двух точках одновременно, что может вызвать трудности, если пользователю нужно быстро переместить одну из двух активных точек касания в новое место: если устройство не обнаружит «отпускание» второго касания до нового касания в другом месте, новое касание может быть не зарегистрировано. Определить, поддерживает ли устройство мультисенсорный ввод, нетрудно. Определить поддержку более чем двух одновременных касаний устройствами Android в данный момент весьма непросто, поскольку нужные данные не раскрываются манифестом android.hardware.touchscreen. Надеюсь, со временем это будет доработано.

    Если наша игра предназначена не для одного определенного устройства, а для нескольких устройств, следует уделить большое внимание размеру и соотношению сторон экрана. Интерфейс, вполне удобный на экране с соотношением сторон 4:3, может оказаться неудобным на устройстве с экраном 16:9. Может быть непросто приспособить один и тот же интерфейс к экранам всех размеров, от 4 до 12 дюймов. Разные пользователи могут держать устройства в руках по-разному; большие пальцы могут естественным образом касаться экрана в разных местах. Места сенсорного управления, удобные для планшетов, могут быть неудобными для телефонов (или наоборот). При этом руки пользователя ни в коем случае не должны загораживать основной экран игрового процесса.

    Перечисленные проблемы можно решить только путем тестирования и ступенчатой разработки; можно использовать ряд приемов, чтобы настроить интерфейс согласно потребностям каждого пользователя. Например, при начальной настройке игра может предложить пользователю расположить большие пальцы на экране наиболее естественным и удобным образом и затем соответственно настроить интерфейс. Все основные сенсорные платформы поддерживают определение размера экрана и разрешения DPI, что позволяет разработчикам принимать оптимальные решения и выбирать версии интерфейса, оптимизированные для планшетов и для телефонов. В идеале интерфейсы должны быть полностью масштабируемыемыми; тем не менее, это может быть непросто, поскольку существует множество устройств с самыми разными размерами экрана.

    Отсутствие обратной связи: кнопки без тактильной реакции

    До недавнего времени интерфейс всех без исключения видеоигр и компьютерных игр имел одну важную общую черту: когда пользователь нажимал на клавишу, он на ощупь чувствовал нажатие клавиши; это позволяло немедленно узнать, что команда пользователя была дана, даже до получения звуковой и визуальной реакции игры. Одна из серьезнейших проблем создания игр с сенсорным управлением заключается в том, что эта проверенная, удобная, привычная и безотказная механическая связь заменяется гладким стеклом, не обеспечивающим никакой тактильной обратной связи. Рассмотрим один из наиболее очевидных недостатков этого изменения: все клавиши на клавиатурах и кнопки на джойстиках и других игровых контроллерах имеют естественные границы; пользователь без труда наощупь определяет эти границы, что помогает поддерживать контакт с интерфейсом и с безупречной точностью выбирать, какие именно кнопки следует нажимать. Кроме того, обычно между соседними клавишами или кнопками есть некоторый промежуток, что дает возможность пользователям естественным образом нажимать точно в середину клавиш и кнопок и, тем самым, повышает точность. Игрок лишается непосредственного ощущения нажатия кнопки и прекращения ее движения, когда она доходит до упора в нажатом положении; поэтому игрок лишается уверенности и определенности в своих действиях; для получения обратной связи ему остается полагаться лишь на частоту опроса устройства и на реагирование игры. Если опираться только на визуальную и акустическую обратную связь, увеличивается задержка между каждым действием и реакцией на него; возникает запаздывание, значительно затрудняющее управление в некоторых типах игр. Наиболее строгие требования к клавишам и кнопкам джойстиков действуют в играх с рукопашными боями и различными единоборствами, поскольку приходится очень быстро обрабатывать команды нескольких игроков. Впрочем, и в классические шутеры, и в аркады намного удобнее играть, используя кнопки и клавиши с тактильной обратной связью и мгновенной реакцией.

    Каким же образом добиться аналогичного удобства от гладкой стеклянной панели? На момент написания этой статьи идеального решения не существовало; шел лишь процесс адаптации. Все потребительские устройства, предназначенные для игр, по-прежнему оснащаются «настоящими» кнопками, но на большинстве устройств с сенсорными экранами таких кнопок нет. Некоторые платформы поддерживают API для применения внешних игровых контроллеров, как проводных, так и подключаемых по интерфейсу Bluetooth. Это вполне разумное решение. Тем не менее, если мы стремимся распространить наши игры в сектор исключительно сенсорных устройств, наши игры должны быть полностью совместимы с сенсорным управлением. Для решения этой задачи можно использовать несколько стратегий.

    Во-первых, на некоторых устройствах можно использовать вибрацию в качестве альтернативы тактильной обратной связи. Вибрацию поддерживают почти все телефоны и ряд планшетов. Такая обратная связь удобна при работе с меню и другими элементами интерфейса; она обеспечивает «ощущение» подтверждения того или иного действия без звука (пользователь может играть в тихом общественном месте). Но это решение ни в коем случае нельзя считать панацеей: вибрация поддерживается не всеми устройствами, уровень обратной связи ограничивается слабой вибрацией, да и задержки существенно больше, чем при нажатии обычных кнопок.

    Акустическая обратная связь также достойна упоминания. Негромкие щелчки или схожие звуки, сопровождающие успешное использование кнопки, могут быть полезны, даже в сочетании с вибрацией. Это неплохое дополнение интерфейса, оно делает интерфейс удобнее, но помогает лишь обойти проблему, а не решить ее. Акустическая обратная связь не годится, если пользователь играет в тихой среде; задержки также представляют собой серьезную проблему для игр, где крайне важна моментальная реакция на случайные события.

    Все перечисленные методики не решают самую важную проблему: пальцы пользователя должны в течение всей напряженной игры оставаться на нужных элементах интерфейса. Виртуальную кнопку невозможно «нащупать», поэтому легко потерять положение кнопки. В результате пользователь будет промахиваться мимо кнопок, и, например, в критический момент вместо открытия огня будет судорожно нажимать пальцем пустое место, что, разумеется, не вызовет восторга. Все эти факторы необходимо внимательно рассмотреть и учесть в процессе первоначального проектирования. В некоторых играх, например, можно вовсе отказаться от фиксированного расположения самых главных кнопок: пусть все важные элементы интерфейса следуют за пальцами пользователя по мере их перемещению по экрану. Если речь идет о «виртуальном джойстике», можно разрешить пользователю продолжить перетаскивание по экрану даже за пределами выделенной области джойстика, если пользователь движет пальцем непрерывно, не отрывая его от экрана.

    Ряд преимуществ есть и у механики «длительного касания», когда пользователь касается и удерживает нажатой определенную область экрана до какого-либо события. Это может быть, например, контекстное меню или дополнительные параметры. Как правило, длительные касания не очень интуитивны, поэтому лучше оставить их для второстепенных функций игры. Впрочем, они могут быть удобны для опытных игроков; с помощью длительных касаний можно фиксировать дополнительное подтверждение для определенных типов игр. Длительное касание должно сопровождаться правильно подобранным использованием вибрационной, акустической и визуальной обратной связи, чтобы сообщить пользователю об успешности выполненной операции (особенно для таких действий как перетаскивание объектов).

    Различное оборудование

    На некоторых платформах эта проблема имеет большее значение, на других — меньшее, но эта проблема в любом случае нуждается в решении, если ваша игра предназначается более чем для одного семейства устройств. За последние несколько лет устройства Android стали более схожими, но все равно существуют значительные различия в качестве сенсорных контроллеров, в количестве одновременно обрабатываемых точек касания, в длительности задержек сенсорного управления и звуковой обратной связи, а также в прочих особенностях оборудования. Для гибридных устройств, таких как смартфоны с клавиатурами, следует подумать об обработке событий, отправляемых ОС Android при физическом включении клавиатуры (ее выдвижении и пр.). Это позволит плавно перейти от использования экранной клавиатуры к вводу с аппаратной клавиатуры с более полным использованием игрового экрана.

    Разработчики музыкальных игр, где большое значение имеет темп и скорость обработки ввода в строго заданное время, должны учитывать, что внутренние аудиосистемы некоторых платформ и устройств работают с длительными задержками, из-за чего синхронизация музыки и действий будет крайне затруднена для пользователей таких устройств. На некоторых платформах низкоуровневые параметры API (например, «встроенные» действия Android) позволяют ускорить обработку ввода и снизить задержки звуковой обратной связи при использовании определенных типов оборудования или в будущих версиях ОС. Со временем вопросы синхронизации звука, связанные с особенностями платформ и оборудования, будут решены путем расширенного тестирования и доработок со стороны производителей устройств, но пока разработчики игр должны отдавать себе отчет о возможных проблемах.

    Итоговые тезисы

    Многие фундаментальные принципы создания игр остаются в силе и при использовании сенсорных экранов. Об этих принципах следует помнить всегда:

    У пользователя должно все получаться, ему должно быть удобно и нетрудно.

    Дайте игрокам возможность сразу почувствовать себя опытными и умелыми — это повысит удобство игры. Это, на самом деле, вовсе не то же самое, что «легкая» игра; это создание ощущения сложности при «обманчиво легкой» игре. Да, разумеется, существуют «хардкорные» геймеры, не терпящие упрощений, и некоторые из нас по-прежнему считают именно такой бескомпромиссный подход единственно заслуживающим уважения; но «хардкорный» подход к играм вообще мало совместим с сенсорными экранами и компактными устройствами. По крайней мере, старайтесь, чтобы пользователю понравилось начало игры.

    Первые несколько минут игрового процесса имеют наиважнейшее значения.

    Необходимо сразу же, как можно скорее произвести на игрока благоприятное впечатление. При разработке обычных игр уже давно наиболее важным отрезком времени считаются первые 15 минут, но в мобильных играх, пожалуй, стоит сократить это время, поскольку мобильные пользователи склонны уделять играм меньше внимания. Постарайтесь полностью «выложиться» в первые две минуты. Если новые пользователи проведут эти две минуты в растущем раздражении, пытаясь привыкнуть к «неполноценному» интерфейсу, то у пользователей вряд ли хватит терпения, чтобы уделить вашей игре длительное время. Разумеется, мы выпускаем не только простые «казуальные» игры, но даже в самых сложных играх все равно существует оптимальный баланс в процессе вовлечения пользователя в игру и обучения его взаимодействию с игрой.

    Старайтесь, чтобы игра ощущалась пользователем как можно более естественно, удобно и привычно.

    Вне зависимости от того, для какой платформы ваша игра предназначалась изначально, при реализации сенсорного управления стремитесь сделать так, чтобы у пользователя возникало ощущение, что эта игра с самого начала делалась для сенсорного интерфейса. «Прикрученные на коленке» сенсорные интерфейсы существенно снижают удовольствие от игрового процесса, что обязательно скажется и на рейтинге игры, и на объеме ее продаж. При разработке в реальных условиях всегда существует целый ряд ограничений; иногда для полноценной переделки игровой механики и интерфейса попросту не хватает времени или средств. Но при любых ограничениях старайтесь сделать как можно более естественный и удобный интерфейс, и ваши усилия в конечном итоге непременно окупятся.

    Перспективы

    Несколько мыслей на будущее. Мир мобильных устройств быстро развивается. В ближайшем будущем появятся и новые интерфейсы, и новые сценарии использования. Уже сейчас можно подключить обычный телефон к телевизору по интерфейсу HDMI, используя при этом телевизор в качестве монитора, а телефон в качестве контроллера. Это станет еще удобнее с развитием беспроводных стандартов HDMI. Некоторые телефоны уже оснащаются компактными проекторами. Теоретически можно играть на большом экране, имея телефон, светлую стену в качестве экрана и компактный игровой контроллер с интерфейсом Bluetooth. Существуют и мощные ТВ на базе Android с различными приставками; все это поможет расширить рыночный охват вашей игры.

    Кроме того, возможно, что сами «экраны» могут смениться виртуальными интерфейсами, которые могут отображаться с помощью особых очков или даже проецироваться на сетчатку глаза пользователя. Возможные разновидности «надеваемых» компьютеров заслуживают упоминания, поскольку они позволяют использовать «жестовые» интерфейсы наподобие Xbox* Kinect*. Такие интерфейсы будут совместимы с сенсорным управлением, но с еще меньшим объемом физической обратной связи (без вибрации и т. п.).

    Впрочем, какими бы путями не развивались мобильные игры, это в любом случае будет увлекательно и интересно.

    Об авторе:

    Джон Бергман (John Bergman) — исполнительный директор компании Guild Software Inc. Джон — опытный разработчик, дизайнер и руководитель онлайн-игр, он основал компанию Guild Software в 1998 году с единственной целью: создавать онлайн-игры нового поколения. Компания Guild Software разработала с нуля полнофункциональный «движок» для MMO-игр, а в 2004 году с успехом выпустила игру «Vendetta Online», которая поступила в продажу во всех крупных розничных сетях.

    Позже эта игра прославилась как первая традиционная компьютерная MMO-игра, перенесенная на мобильную платформу; в 2011 году партнеры по реализации этого проекта, корпорации Verizon и Motorola, провели обширную кампанию телевизионной рекламы. Вне работы Джон занимается обучением начинающих разработчиков игр, консультирует перспективные новые проекты и участвует в работе различных связанных с играми консультативных советов в нескольких университетах.

    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 infully 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 and the Intel logo are trademarks of Intel Corporation in the US and/or other countries.

    Copyright © 2012 Intel Corporation. All rights reserved.

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

  • Developers
  • Android*
  • Android*
  • URL

  • Build An Android Mobile Application Binary Using Intel App Dev Center Build Web Service

    $
    0
    0

    The App Dev Center build web service can be used to build a mobile application binary without going through the XDK. 

    In order to use the App Dev Center build web service, developers must email html5tools@intel.com from the email address of their valid account to be approved for use of these services and obtain a valid Customer ID and a valid Partner Code to identify their requests.

    Commands

    This command will return a link to an iOS or Android binary of a preconfigured application

    This command will return the build status for the application on the specified platform
    This command will create a new application
    Returns a certificate signing request
    This command will return a list of applications for a particular account
    This command will return a list of builds previously made for a particular application
    This command returns the certification type
    This command uploads a certificate and private key or a P12 file containing both in order for a particular account to build iOS applications
    This command will upload several icon and splash images at once
    This command uploads the large launch icon for an iOS application
    This command uploads the large splash image for an iOS or Android application
    This command will upload a provisioning profile for an iOS application.
    This command will upload and save the push certificate for an iOS application.
    This command will upload and save the small icon image for an application
    This command uploads the small splash image for an iOS or Android application

    This support function will determine if a x509 certificate and private key are related.

    NOTE: Use of the build web service is primarily intended for partners who do a large number of builds and need to automate the process. It is not recommended for the general user who builds apps one at a time. Most users should perform builds via the XDK or App Dev Center. 

    For more information,  you can go to Intel Web Service API Online documentation

  • Android app development
  • Icon Image: 

    Blast from My Past, How Meteor's Helped Me Understand Touch Sensors

    $
    0
    0

    After getting my Star Trek on while reading about writing code for the sensors on the Intel® Ultrabook at codeproject.com, I was pleased to see that Adrian Atkison had submitted an article titled, “Meteor Madness.” The game is reminiscent of way too many hours I spent on an Atari* avoiding and destroying astrological objects that can be found just outside Mars in our solar system. One of Mr. Atkison’s innovations is allowing both touch and classic keyboard control simultaneously during game play.  Since I have a historical feel for the game I found the explanations in this article particularly helpful in getting my new-to-sensors head around what one can do when going from traditional input devices to a touch input. Well done Adrian, I’m going to go blow up some space rocks.


    Meteor Madness Article –
    http://www.codeproject.com/Articles/480771/Meteor-Madness

    Gameplay Demo on Youtube –
    http://youtu.be/7PMhxBsmMLM 

    ‘Roid Rage Game on Windows 8 Store –
    http://apps.microsoft.com/windows/en-us/app/roid-rage/2d6287ff-e08f-4499-8245-d00899fd5824

     

  • Tim Duncan touch sensor codeproject contest
  • Icon Image: 

    Running Out of Gas? Intel® processor-based Ultrabook™ Sensors to the Rescue!

    $
    0
    0

    As I begin my 3rd article on what I’ve learned from about development for an Ultrabook™ system on codeproject.com, I feel I need to bring the subject closer to earth. I am so glad Dr. A. Bell submitted his article to the site called, “Road and Driving Pattern Analyzer using Ultrabook™.” I drive about 15,000 miles per year for commuting and vacations, some years more. One such vacation was a 6 week journey through the southwestern United States with my wife and dog.  Now if you’ve ever watched Roadrunner* cartoons you have a good idea where we were. We saw so many beautiful vistas and learned a little as well.  There are phenomenal landscapes and fascinating pre-history, but there's also a lot of time on the road looking at different shades of dirt.  For me, I spend a fair amount of the time playing with various calculations in my head like trip miles per hour including gas/potty/food stops or more importantly, is there enough gas in the tank to get to the next fueling station (a real concern when crossing Death Valley for instance).  Too bad I didn't have a device and application that approaches what Dr. Bell's analyzer does, I'd have never got bored.  Check out the references at the bottom of the article - they really help explain the possibilities of combining generally available information systems like web maps with Intel processor-based Ultrabook sensor specific data to create compelling and often even useful applications.  Oh well, now that I read about connecting the app to Microsoft* Bing* and my own Ultrabook system's GPS we just may have to bring the kids along on the next trek.

    Google* Maps Image of Our Route

    Road and Driving Pattern Analyzer using Ultrabook™ -
    http://www.codeproject.com/Articles/481804/Road-and-Driving-Pattern-Analyzer-using-Ultrabook

  • intel ultrabook tim duncan GPS maps
  • Icon Image: 

    Wakelocks: Detect No-Sleep Issues in Android* Applications

    $
    0
    0

    Abstract

    Android* applications may increase battery consumption significantly if they use wakelocks improperly. In this document, we will give some hints and tips on how to identify No Sleep bugs related to wakelock misuse.

    1. Introduction
    2. Wakelock
    2.1. What is it?
    2.2. Android User Wakelocks
    2.3. Android Kernel Wakelocks
    2.4. No-Sleep bugs
    3. Identifying No Sleep ugs
    3.1. Using adb
    3.2. Using BetterBatteryStats application
    4. Test case
    5. Conclusion
    6. Reference

    1. Introduction

    Limiting battery power consumption is essential for smartphones. To get the best autonomy possible, Android OS is designed to opportunistically go into sleep mode as soon as it detects no user activity on the system. Some applications require the device to stay on even if there is no user interaction for a long time. Examples of this are watching a video, listening to music, using GPS, and playing a game. Android provides such a mechanism for the OS or applications in order to keep the device awake. This mechanism is called a wakelock. For more details, please read Christopher Bird’s article: “Wakelocks for Android”.

    The introduction of such a mechanism puts the responsibility of managing the component’s activities on the application developer. If used incorrectly, the application can drain the battery significantly even when the application is not running in the foreground.

    2. Wakelock

    2.1. What is it?

    A wakelock is a software mechanism to control the power state of the host device. The OS exports explicit power management handles and APIs to specify when a particular component needs to stay on, or awake, until it is explicitly released from duty.

    The wakelock mechanism is implemented in two levels: user and kernel. The figure shows the internal design of Android wakelock implementation. The user wakelock can be utilized by either high-level OS services or applications and is provided by the power management service. It allows an application to control the power state of the device. A kernel wakelock is held by the OS kernel or a driver. A user wakelock is mapped to a kernel wakelock. Any active kernel-level wakelock prevents the system from being suspended to ACPI S3 (suspended to RAM) state, which is the highest power saving state for mobile devices.

    2.2. Android User Wakelocks

    The Android framework exports the wakelock mechanism through the PowerManager.Wakelock class and identifies four types of user wakelocks:

    Flag ValueCPUScreenKeyboard

    PARTIAL_WAKE_LOCK

    On

    Off

    Off

    SCREEN_DIM_WAKE_LOCK

    On

    Dim

    Off

    SCREEN_BRIGHT_WAKE_LOCK

    On

    Bright

    Off

    FULL_WAKE_LOCK

    On

    Bright

    Bright

    Note that since API level 17, FULL_WAKE_LOCK has been deprecated. Applications should use FLAG_KEEP_SCREEN_ON.

    Wakelocks can be acquired to force some of the components (CPU, screen, and keyboard) to stay awake.

    Use special caution with the PARTIAL_WAKE_LOCK as the CPU will continue to run regardless of any display timeouts or the state of the screen and even if the user presses the power button. This may lead to silent power drain as the phone looks like it is in standby mode (screen is off), but is actually fully awake.

    In all other wakelocks, the user can still put the device to sleep using the power button. All wakelocks, except partial wakelocks, will be implicitly released after the power button is pressed.

    This is how applications can hold a wakelock. It is basically an Acquire/Release mechanism. The application acquires a wakelock when it needs some components to stay on. When those are not needed anymore, the wakelock needs to be released.

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
    wl.acquire();
    ..screen will stay on during this section..
    wl.release();

    2.3. Android Kernel Wakelocks

    Kernel wakelocks are low-level wakelocks held by the kernel. They can be acquired/ released internally from the kernel. As such, application developers have less direct control on them, but an application’s behaviour can indirectly trigger these wakelocks and increase battery consumption inadvertently.

    Here are examples of kernel wakelocks.

    Wlan_rx: Held by the kernel when data is sent or received over Wi-Fi*.

    PowerManagerService: Is the container for all partial wakelocks.

    Sync: Held while the sync process is running.

    Alarm_rtc: Handles the alarm (when an application or process checks periodically on something).

    Main: Keeps the kernel awake. This is the last one to be released when the system goes to suspend mode.

    2.4. No-Sleep bugs

    The application has to release every wakelock it acquires at some point to allow the system to go back to a deep sleep mode. This acquire/release mechanism may lead to some bugs if the wakelock is never released. A wakelock remains held even if the application holding it is not running in the foreground anymore. A wakelock is released when it is explicitly released by a release call or if the application is actually killed (force close). Leaving some wakelocks held prevents the system from going into deep sleep mode even if there is no activity, significantly increasing the power drain and silently reducing the battery autonomy. This is called a No-Sleep bug. Due to the event-driven nature of Android, developers may not think of all the code paths that their applications had acquired wakelocks and, therefore, need to close. This type of bug is called a No-Sleep bug code path.

    Another occurrence of this type of bug is when the release happens before the wakelock has been effectively acquired. This can happen in multithreaded code where the acquisition and release of the wakelock happen in different threads. This is called a No-Sleep bug race condition.

    The last issue is the No-sleep dilation, where the wakelock is acquired longer than what is actually necessary.

    Why are these issues important to look at? According to a study made by P. Vekris: “55% of 328 applications using wakelocks do not follow our policies for no-sleep bugs” [2012]. Some major applications have been released with No-Sleep bugs. So developers need to be aware of this specific point in order for their applications to run optimally.

    3. Identifying No Sleep bugs

    The no sleep bug can be tackled in two ways: either a static analysis doing a code path scanning or dynamically at run time. In this paper we will focus on run-time analysis.

    This method does not guarantee you’ll find all the wakelocks bugs in an application. It will however help you spot some wakelock issues if they occur during run time. To identify a wakelock issue, you need to follow a code path where the wakelock is not released. Testing an application against no sleep bugs involves manipulating the application, trying different ways to exit it, at different places in the application to see if a wakelock persists.

    In some cases, it may be necessary to prevent the system from going into deep sleep even if the application is not in the foreground anymore. An application may need to perform a task in the background. This is the case, for example, if the application has to perform a long download: a video or game dataset. The application may be put in the background by the user while it’s downloading, but the phone should stay awake until the download is completed. In that case, the application may hold a wakelock until the download is completed. Of course, you should check that the wakelock is released at some point. For example, if the phone loses network connection in the middle of a download, the phone should not remain awake if the action cannot be performed anymore.

    In summary, identifying a No Sleep bug is very context dependent. There is no predefined criterion that allows someone to easily identify this issue. Only common sense can assess these types of bugs.

    3.1. Using adb

    The simplest tools to look at wakelocks are shell commands.

    To get a full picture of the kernel wakelocks, type:

    adb shell cat /proc/wakelocks

    namecountexpire_countwake_countactive_sincetotal_time
    "PowerManagerService"1502000337817677431
    "main"15000984265842688
    "alarm"151207920217778251643
    "radio-interface"1600016676538930
    "alarm_rtc"8044001204136324759
    "gps-lock"100010753659786
    namesleep_timemax_timelast_change
    "PowerManagerService"957294091221409216636679723417252748
    "main"02124247323559498127170228
    "alarm"2176173620473579769419723371461242
    "radio-interface"016593284969486387144974
    "alarm_rtc"1200253446201660829365019483176054624
    "gps-lock"01075365978637632803440

    For images using kernel 3.4 or higher, use “adb shell cat /sys/kernel/debug/wakeup_sources.” Even though it gives all the information, this format is not very user friendly. The tools we are introducing below are much handier.

    A simple way to check a specific application is by using “adb shell dumpsys power.” Below is a typical output of this command. You can see in red the user wakelocks present at the time the command was issued. This command gives a snapshot of the user wakelocks present in the system.

    Power Manager State:
    mIsPowered=true mPowerState=3 mScreenOffTime=1618305 ms
    mPartialCount=3
    mWakeLockState=SCREEN_ON_BIT
    mUserState=SCREEN_BRIGHT_BIT SCREEN_ON_BIT
    mPowerState=SCREEN_BRIGHT_BIT SCREEN_ON_BIT
    mLocks.gather=SCREEN_ON_BIT
    mNextTimeout=2382037 now=2378097 3s from now
    mDimScreen=true mStayOnConditions=3 mPreparingForScreenOn=false mSkippedScreenOn=false
    mScreenOffReason=0 mUserState=3
    mBroadcastQueue={-1,-1,-1}
    mBroadcastWhy={0,0,0}
    mPokey=0 mPokeAwakeonSet=false
    mKeyboardVisible=false mUserActivityAllowed=true
    mKeylightDelay=6000 mDimDelay=587000 mScreenOffDelay=7000
    mPreventScreenOn=false mScreenBrightnessOverride=-1 mButtonBrightnessOverride=-1
    mScreenOffTimeoutSetting=600000 mMaximumScreenOffTimeout=2147483647
    mLastScreenOnTime=27380
    mBroadcastWakeLock=UnsynchronizedWakeLock(mFlags=0x1 mCount=0 mHeld=false)
    mStayOnWhilePluggedInScreenDimLock=UnsynchronizedWakeLock(mFlags=0x6 mCount=0 mHeld=true)
    mStayOnWhilePluggedInPartialLock=UnsynchronizedWakeLock(mFlags=0x1 mCount=0 mHeld=true)
    mPreventScreenOnPartialLock=UnsynchronizedWakeLock(mFlags=0x1 mCount=0 mHeld=false)
    mProximityPartialLock=UnsynchronizedWakeLock(mFlags=0x1 mCount=0 mHeld=false)
    mProximityWakeLockCount=0
    mProximitySensorEnabled=false
    mProximitySensorActive=false
    mProximityPendingValue=-1
    mLastProximityEventTime=0
    mLightSensorEnabled=true mLightSensorAdjustSetting=0.0
    mLightSensorValue=11.0 mLightSensorPendingValue=10.0
    mHighestLightSensorValue=47 mWaitingForFirstLightSensor=false
    mLightSensorPendingDecrease=false mLightSensorPendingIncrease=false
    mLightSensorScreenBrightness=42 mLightSensorButtonBrightness=0 mLightSensorKeyboardBrightness=0
    mUseSoftwareAutoBrightness=true
    mAutoBrightessEnabled=true
    creenBrightnessAnimator:
    animating: start:42, end:42, duration:480, current:42
    startSensorValue:47 endSensorValue:11
    startTimeMillis:2361638 now:2378092
    currentMask:SCREEN_BRIGHT_BIT
    mLocks.size=4:
    SCREEN_DIM_WAKE_LOCK          'StayOnWhilePluggedIn_Screen_Dim' activated (minState=1, uid=1000, pid=388)
    PARTIAL_WAKE_LOCK             'StayOnWhilePluggedIn_Partial' activated (minState=0, uid=1000, pid=388)
    PARTIAL_WAKE_LOCK             'HDA_PARTIAL_WAKE_LOCK' activated (minState=0, uid=10046, pid=4690)
    PARTIAL_WAKE_LOCK             'AudioOut_2' activated (minState=0, uid=1013, pid=157)
    mPokeLocks.size=0:

    To identify if any wakelocks still held after an application has been put in background, you can follow this process:

    1. Connect the device to USB.
    2. Launch the application and play with it.
    3. Press the power button to go to sleep mode or exit the application in some way.
    4. Wait for about 20 sec.
    5. Type the following instruction in command line:
    > adb shell dumpsys power
    6. Check if there are any PARTIAL_WAKE_LOCKs like this one for example:
    PARTIAL_WAKE_LOCK       ‘AudioOut_2’ activated(minState=0, uid=1013, pid=157)
    7.Repeat step 5 every 15 sec 3 to 5 times. If the result stays the same, there may be an issue.

    3.2. Using BetterBatteryStats application

    BetterBatteryStats* (https://play.google.com/store/apps/details?id=com.asksven.betterbatterystats&hl=en) is an Android app by Sven Knispel that you can buy on Google Play. It collects information that allows you to spot battery drain, especially wakelock issues.

    First, by selecting the ‘Other’ entry, you can check the deep sleep and awake modes versus the total time. Ideally, most of the time, the phone should be in Deep Sleep if it is not in use.

    You can also compare the Awake time vs. the Screen On time to see when there is actual activity. Under normal conditions, the Screen On time and the Awake time should be close.

    You can check the battery charge evolution and the awake, Screen On, and Wi-Fi* states over time.

    Then you can check the kernel wakelocks. You can check the time spent within each kernel wakelock type as well as the count. High time or high counts may be symptomatic of a problem. From this report you cannot link a hotspot to a specific application or process but you can spot a specific behaviour that may be triggered by a specific application.

    In the Kernel Wakelock report, the line “PowerManagerService” aggregates the time spent in user wakelocks. If this line shows a hot spot, you can drill down by checking the Partial Wakelock report.

    Most of the time, the partial wakelock refers to the application that holds it. It’s a great help to find the culprit. Though some times, some activities may be launched by other apps. For example, a game may play sound through the AudioOut channel assigned to the Android Media gallery. If not coded properly, it would be the game’s fault for not closing the sound channel. It is never the Android Gallery’s fault.

    The AlarmManager may signal that wake ups were caused by alarms or that an application has made numerous alarm modifications. You may want to check the Alarm section but it will only work if you have a rooted image.

    Network entry is also accessible only on rooted images. It can be useful if you suspect some high traffic on the network. The multipdp/svnet-dormancy kernel wakelock may indicate that you also have some high network usage.

    4. Test case

    Let’s consider a real case using a game. Start it and play for about five minutes, and then exit the game in an unusual way. In our case we forced the exit by pressing the Home button. The music stopped, and the home screen displayed. From a user standpoint, everything looks fine. After a few minutes of inactivity the screen goes dark as expected. Let’s leave the phone in this state for about half an hour and then check it with BestBatteryStats. On the “Other” screen, you can see that the phone remained awake despite the fact the screen was not on. You can also see that the battery depletion rate is at 8.5%/hr. So in this state, the phone with a full battery will last no more than 12 hrs.

    Now let’s look at the Kernel wakelocks. We can see that two kernel wakelocks remain despite the fact that there is no activity. One is the PowerManagerService, which means that there is a user partial wakelock, and the other is an AudioOutLock wait lock. Let’s have a look at the Partial wakelock screen.

    Looking at the partial wakelock screen, we can see that an audio channel is still open with the media gallery application. This is curious as the media gallery application was not used explicitly by the user. The game actually launched the Media Gallery for the game’s music playback. The developer has simply forgotten to close the audio channel when the application is interrupted by the home button. The developer needs to take this case into consideration and modify the application accordingly.

    5. Conclusion

    Wakelocks are very useful and powerful tools. But if misused, they can have a very negative effect on the device battery life, considerably impacting the user experience. It is important for developers to check during QA that their code is not causing any No Sleep bugs. They should consider using the available tools to analyse the battery impact of their application in real life usage and try to limit their impact on the customer device as much as possible.

    6. Reference

  • Developers
  • Android*
  • Android*
  • URL
  • “一次编写,随处运行” Intel HTML5技术研讨会

    $
    0
    0

    HTML5 是一种开放标准。通过使用此标准,开发人员只需编写一次程序,即可在任何地方运行。 这一跨平台方法能够显著增加开发人员的总体潜在受众,同时在不同屏幕尺寸上为用户带来更一致的体验。因此,HTML5 是应用程序开发领域的未来趋势,英特尔认为需要帮助经验丰富的开发人员迁移到这一跨平台方法,并支持新的开发人员借助这一出色的全新方法快速跟上行业发展步伐,以确保这些开发人员能够在几乎所有现代计算平台上部署其应用程序和游戏.

    最近在上海举办的“一次编写,随处运行” Intel HTML5技术研讨会,给软件开发人员有机会:

    •  率先领略HTML5应用在英特尔平台上的全新体验; 
    • 了解英特尔平台上HTML5的软件开发工具;
    •  英特尔技术工程师就您关心的技术焦点等问题展开深入探讨。

    讲座内容如下(我们特别记录了讲座实况,使不能现场参加的开发人员也能有机会了解内容):

    HTML5简介 (50mins) (讲座视频
    HTML5是用于取代1999年所制定的 HTML 4.01 和 XHTML 1.0 标准的 HTML 标准版本。本讲座主要介绍HTML5标准的发展历程、HTML5的特点和优势以及HTML5标准中新加入的功能。

    开发高性能HTML5应用 (60mins) (讲座视频
    软件性能对于HTML5应用而言尤其重要。本讲座将分享一些开发高性能HTML5应用的最佳实践,包括可能带来百倍性能提升的编程模式,以及各种编程模式导致不同性能的底层原因。同时,我们会介绍Intel开发的HTML5性能分析工具。

    Intel HTML5应用开发工具简介 (90mins) 

    Intel开发了一系列HTML5应用开发工具,其中包括HTML5应用开发集成环境Intel XDK和HTML5应用移植工具Intel HTML5 App Porter。这些工具可以有效的帮助开发者快速创建、开发、测试、调试、打包、部署和移植HTML5应用程序。

    1. 基于WebRTC*的协作服务平台
    2. 从本地应用到HTML5应用
    3. 英特尔HTML5开发环境

     

  • Developers
  • Intel AppUp® Developers
  • Partners
  • Professors
  • Students
  • Android*
  • Apple iOS*
  • Apple Mac OS X*
  • Microsoft Windows* 8
  • HTML5
  • HTML5
  • Beginner
  • Intermediate
  • Intel® HTML5 Development Environment
  • URL
  • Getting started
  • Improving performance
  • Viewing all 531 articles
    Browse latest View live


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