digit devworx march 2013

Upload: poorna-chandran

Post on 04-Jun-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/13/2019 Digit Devworx March 2013

    1/100

    To

    A 9.9 Media Publication

    YOUR GUIDE TO MOBILE APPLICATION DEVELOPMENT

    Intro to Android | The Android SDK| Developing for Android |GUI Development| The Android NDK | Developing for Android x86|

    Debugging on Android | Intel Hardware Accelerated

    Execution Manager

  • 8/13/2019 Digit Devworx March 2013

    2/100

  • 8/13/2019 Digit Devworx March 2013

    3/100

    Android

    Intel

    on

    Architecture

  • 8/13/2019 Digit Devworx March 2013

    4/100

    05ANDROID NDKGetting under the hood of Androidand refining your app would need you

    to be familiar with native code.

    C O N T E N T S

    Interm

    ediate

    Advanc

    ed

    03DEVELOP FOR

    ANDROIDAll you need to know whiledeveloping for Android

    07DEBUGGING

    ON ANDROIDWith every product comes

    troubleshooting.

    01INTRODUCTIONThrough the course of this booklet,

    youd be able to develop an appfor the Android platform and findrelevant details to cater to the Intel

    x86 Android portfolio.Beginne

    r

  • 8/13/2019 Digit Devworx March 2013

    5/100

    02GETTING STARTEDThe Android SDK when paired with anIDE and API libraries, platform toolsgives you a complete environment.

    06DEVELOPING

    FOR X86x86 is no longer restricted to PC.Heres quick way to get started withAndroid for Intel devices.

    04GUI DEVELOPMENTUser interface is a driving factor in thesuccess of your app. Here are tips tostand out of the crowd.

  • 8/13/2019 Digit Devworx March 2013

    6/100

    EDITORIAL

    Assistant Editor

    Nash David

    Writers

    Ankit Mathur & Soham Mondal

    with inputs from Intel

    DESIGN

    Sr. Creative DirectorJayan K Narayanan

    Sr. Art Director

    Anil VK

    Associate Art Directors

    Atul Deshmukh & Anil T

    Sr. Visualisers

    Manav Sachdev & Shokeen Saifi

    Visualiser

    Baiju NV

    Consulting Designer

    Vijay Padaya

    BRAND

    Product Manager

    Arun Yadav

    Manager Online

    Shauvik Kumar

    Asst. Product Manager

    Kshitij Garg

    Cover Design

    Vijay Padaya

    9.9 Mediaworx Pvt. Ltd.No part of this book may be reproduced, stored, or transmitted in any form

    or by any means without the prior written permission of the publisher.

    March 2013Free with Digit. If you have paid to buy this book from any

    source other than 9.9 Mediaworx Pvt. Ltd., please write to

    [email protected] details

    Android for X86

    > Your guide to mobile application development >

  • 8/13/2019 Digit Devworx March 2013

    7/100

    CHAPTER 1

    Introduction

    Through the course of this booklet, you'd be able to develop

    an app for the Android platform and also find the relevant details

    to cater to the Intel x86 segment in the Android portfolio.

  • 8/13/2019 Digit Devworx March 2013

    8/100

    6 ANDROID FOR X86

    As most would believe Android is a mobile oper-ating system that is opensource and free for anyoneto use, modify, develop

    and distribute. Nonetheless, there are some who rather prefer calling it

    an application stack where components are easily switchable suitable and

    exciting alternatives, thereby increasing variety. The only restriction you

    could think of would be modification of the core platform (such as not bun-

    dling the Play Store, Gmail or Calendar). Including these requires a licence

    and ensure that you comply with Android specifications while marketingyour application. While this has made it difficult for manufacturers to dif-

    ferentiate their products in the market, it has enabled Google to keep the

    concerns of fragmentation at a minimum and made it easier to consolidate

    the Android market.

    This has however never stopped hardware manufacturers from selling

    products after putting on custom skins (Sense UI by HTC) and enabling

    proprietary device specific features (Multiwindow and the floating videoplayer by Samsung) on their respective devices.

    Open Handset AllianceAndroid is led by an entity known as the Open Handset Alliance, the organi-

    sation that made such an open platform possible. Though it is led by Google,

    there are a total of 84 members (as of today) who have made some major

  • 8/13/2019 Digit Devworx March 2013

    9/100

    7ANDROID FOR X86

    contributions towards the development of the Android platform. Of these,

    34 of the member companies are founding members which include Mobile

    operators such as NTT DoCoMo, and T-Mobile; semiconductor companies

    such as Intel, Nvidia, Qualcomm and Synaptics; handset manufacturers suchas Samsung, HTC, Sony, LG and Motorola; and software companies such

    as eBay and Nuance Communications. Since then, most major companies

    related to electronics, communications and software have joined the effort

    of making Android better day by day.

    These are those companies that not only support the ecosystem by

    bringing in devices that run Android, but also invest a significant amount of

    money and resources into it. These members who produce Android deviceshave to sign a contract that they will always support the community by not

    selling incompatible versions of Android. This not only results in much

    faster development of the platform, but an eventual merging of most of the

    features into the mainline, that a particular manufacturer develops. This

    reduces effort and develops trust among the competing manufacturers in

    the market, which are also benefits the community which has grown with

    a huge number of modders and hackers who continue to make their owninnovations on the software.

    Developer concernsFrom a developer's perspective, however, this shouldn't cause many prob-

    lems because Android apps are promised to run similarly from the ground

    up, as long as you take into consideration the varying screen sizes and

    resolutions. This might be an advantage for many, but it is also the reasonwhy many developers choose iOS first over Android, though that gap is

    narrowing day by day. The very fact that iOS is restricted to one mobile

    handset and tablet which is equally popular makes development and testing

    very easy, due to which developers and designers are able to offer a much

    better overall finish and user experience to their apps. Another reason

    might be the perception that iOS users are more likely to actually make a

    purchase and invest in an app than their Android counterparts who oftenuse cheaper handsets which are often outdated and are not even available

    in the market. The main problem with such devices firstly is that they are

    not even available for testing by the developer and moreover they run much

    older versions of Android because the carrier or device manufacturer haven't

    released an update to the latest Android version. Most popular developers

    have often stated that they have to test the app for hundreds of handsets

  • 8/13/2019 Digit Devworx March 2013

    10/100

    8 ANDROID FOR X86

    before actually releasing it in the app store.

    Keeping aside the downsides though, Android app development is

    actually much easier and offers much more flexibility. Android apps are

    allowed to change almost any component of even the base system, rangingright from the launcher to even the messaging and music application. This

    is the kind of customisability that iOS will never be able to provide. What's

    more apps are able to share data among themselves much more easily

    using intents, which is a great way to touch the boundaries of freedom.

    Android development also runs at a much faster pace than its competitor,

    so most of the quirks or irritations that you might have usually tend to get

    addressed in the next release or so. This might also mean that you have tomake sure your app works for users right from Android 2.3 Gingerbread

    to JellyBean 4.1/4.2.

    A brief historyAndroid has grown a lot through the past few years, when it first came out

    in November 2007 as a beta, it already had an SDK to go with it. The first

    official release was however only a year later in September 2008 with fea-tures such as the Android Market (now known as the Play Store), camera,

    Wi-Fi, Bluetooth and sync support in addition to instant messaging. The

    first major release that turned out to be quite popular with its dessert name

    was Android 1.5 Cupcake. This release brought along with it some major

    features and refinements like screen rotation, on screen keyboard with text

    prediction, app widgets, Bluetooth audio streaming with A2DP and a newer

  • 8/13/2019 Digit Devworx March 2013

    11/100

    9ANDROID FOR X86

    Linux kernel 2.6.27. Eventually development sped up with release of more

    candies like Donut, Eclair and Froyo. Each of which brought about a slew

    of features like a new Text to Speech Engine, a new search framework along

    with gestures and accessibility support for Donut. Android 2.0 Eclair, asexpected turned out to be a big release from a user's perspective, which

    also introduced the much popular WebView support for developers. But

    the next release i.e. Froyo, turned out to be a bounty for developers which

    featured cloud to device messaging for two way push notifications, crash/

    bug reporting and allowed apps to be installed on the external SD card.

    The most popular platform till date however, which still holds a sizeable

    portion in the amount of active Android devices has been Gingerbread or

    Platform version API level Version Code

    Android 4.2 17 JELLY_BEAN_MR1

    Android 4.1, 4.1.1 16 JELLY_BEAN

    Android 4.0.3, 4.0.4 15 ICE_CREAM_SANDWICH_MR1

    Android 4.0, 4.0.1, 4.0.2 14 ICE_CREAM_SANDWICH

    Android 3.2 13 HONEYCOMB_MR2

    Android 3.1.x 12 HONEYCOMB_MR1

    Android 3.0.x 11 HONEYCOMB

    Android 2.3.4

    Android 2.3.3

    10 GINGERBREAD_MR1

    Android 2.3.2

    Android 2.3.1

    Android 2.3

    9 GINGERBREAD

    Android 2.2.x 8 FROYO

    Android 2.1.x 7 ECLAIR MR1

    Android 2.0.1 6 ECLAIR_0_1

    Android 2.0 5 ECLAIR

    Android 1.6 4 DONUT

    Android 1.5 3 CUPCAKE

    Android 1.1 2 BASE 1_1 (Internally known as Petit Four)

    Android 1.0 1 BASE

  • 8/13/2019 Digit Devworx March 2013

    12/100

    10 ANDROID FOR X86

    Android 2.3. This release added some major features like NFC, Gyroscope

    and SIP protocol support. It also added several improvements to the UI and

    available controls. Later came Honeycomb with major focus for tablets and

    a UI overhaul which was to be integrated in Ice Cream Sandwich later. ICScame with support for Android Beam, unified social API, VPN client API,

    Text to Speech API and most importantly unified framework for phones

    and tablets. Jelly Bean, the most recent revision has added features for

    developers like USB Audio output, app encryption, app verification, script

    intrinsics and filterscript support.

    The API levels mentioned in the table represent a unique integer valuethat specifies the corresponding revision of the framework API. It is used to

    identify the minimum, maximum and target API level at which the applica-

    tion can work. Hence, it is used to manage the compatibility requirements

    of various Android apps, who need to specify their API requirements in

    their manifest. The version code on the other hand have always represented

    the official name by which newer Android versions are known as. These

    have been named alphabetically after desserts ever since the Android 1.5version which was called Cupcake. There have been no official names

    starting with A and B, though there have been rumours that these had

    some internal references within the company.

    Android Architecture

    Nothing beats the way architecture has been explained in the official docs,

    still the overall software stack consists of overall five components thatmake the whole platform work. These are a set of loose software layers that

    work with each other like any other computer operating system, just that

    they are heavily optimised specifically for mobile environments. The fact

    that it is based on the Linux kernel results in the fact that it is even more

    robust, community tested and portable to run on almost any other device.

    The dalvik virtual machine provides a layer of abstraction, just like a Java

    VM, so that apps are able to run without worrying about the underlyingplatform of the mobile or tablet device. This is precisely the reason why

    Android has been easily ported to unconventional devices like watches,

    refrigerators and in-car entertainment systems.

    Kernel

    As, we discussed before, Android is based entirely on the Linux kernel

  • 8/13/2019 Digit Devworx March 2013

    13/100

    11ANDROID FOR X86

    which directly interfaces with the

    mobile hardware to handle drivers

    for each functionality and handlesmemory, power, network and process

    management. This is the layer on which

    the Dalvik Virtual Machine and core

    libraries run. The kernel being open

    source has prompted a number of hob-

    byist hackers and modders to release

    their own popular versions of kernelsfor specific devices. It has often been an

    important topic of discussion for people

    who want to tweak their CPU gover-

    nors, I/O schedulers and custom kernel

    modules. This has given rise to an inter-

    esting community that customises their

  • 8/13/2019 Digit Devworx March 2013

    14/100

    12 ANDROID FOR X86

    devices to suit their preferences. There have been instances when Android

    has been ported to run even on phones that do not officially bundle it.

    DalvikDalvik is the most important component that runs Android applications.

    It resembles the Java Virtual Machine in the sense that code written in Java

    is converted to bytecode and then into a Dalvik executable (.dex) which is

    done with the dx tool. This particular format has been used because it is

    very beneficial for memory and power limited devices and runs withoutany swap space available, as opposed to Java which has considerably higher

    requirements.

    Libraries

    Libraries are exactly what they sound like low level software bundles

    that handle basic device functions such as 3D hardware acceleration with

  • 8/13/2019 Digit Devworx March 2013

    15/100

    13ANDROID FOR X86

    OpenGL, Surface Manager as the display subsystem to handle multiplelayers of software applications. This layer includes an implementation of

    the standard C system library (libc). The SQLite database used for storing

    information is also an important component that is used extensively.

    ApplicationsApplications are the components that app developers like you or me develop.

    These can be system apps like SMS messaging, E-Mail, Home Launcher,Contacts, Dialer, Settings etc. Basically, anything that is presented in front

    of you is part of app that has a specific lifecycle.

    App FrameworksApp frameworks are a set of services that expose an API and provide access

    to device functions like displaying views, accessing data, pushing notifica-

    tions to the main notification bar, application lifecycle management etc.

  • 8/13/2019 Digit Devworx March 2013

    16/100

    14 GETTING STARTED

    CHAPTER 2

    Getting StartedWHILE THE ANDROID SDK allows you to get started with

    app development, when paired with an IDE and API libraries,

    platform tools, ADT plugin and the Android system image it givesyou a complete environment to ease and supplement the pro-

    cess of development, testing and debugging your application.

  • 8/13/2019 Digit Devworx March 2013

    17/100

    15GETTING STARTED

    Basic PrerequisitesThe basic system requirements listed by the Android developer website

    are as follows:

    Windows XP (32-bit), Vista (32- or 64-bit), or Windows 7 (32- or 64-bit)

    Mac OS X 10.5.8 or later (x86 only)

    Linux

    GNU C Library (glibc) 2.7 minimum.

    Ubuntu version 8.04 or later.

    64-bit distributions should run 32-bit applications.

    The SDK and other tools procured from the official website have beentested for Linux only on the Ubuntu distribution. Though other distros

    might have their own packages in their official repositories which are com-

    munity tested. We would recommend using those instead, because setting

    up and updating them would be much more easier and streamlined.

    Other than these platform requirements, Android SDK requires JDK 6

    (Java Development Kit) to be installed on your operating system. It should

    be stressed specically that Gnu compiler for Java (GCJ) is not supportedand older versions of the JDK are also incompatible. By default, the IDE

    that is supported by the Android SDK is Eclipse ( At least Eclipse Helios

    3.6.2), which is actually even bundled with the ADT bundle for your spe-

    cific platform.

    Getting the SDK

    The SDK can be procured from the official website and is available aspart of an ADT bundle or as a separate SDK Tools bundle if you have a

    development environment already set up. As mentioned before, the ADT

    tools bundle already includes everything you need in order to get started

    with running a new development environment for Android including the

    Eclipse IDE. The package is available for all the three platforms including

    Linux, Windows and Java. It can be downloaded from the Android SDK

    download page (dvwx.in/VKWyKI), which will show you a Download theADT Bundle for Linux/Windows/Mac button on the right as per your

    present platform. If you want to download it for a platform which is not

    your current one, you can click the Download for other platforms link at

    the bottom and it will show you the list of platforms which are supported

    for the ADT Bundle as well as SDK Tools.

    If you feel that you need just the SDK and have to integrate it with some

  • 8/13/2019 Digit Devworx March 2013

    18/100

    16 GETTING STARTED

    existing IDE, you can click the Use Existing IDE link, which will show

    you the Download SDK Tools for Linux/Windows/Mac button.

    Setting up with the ADT bundleTo install and set up the ADT bundle, all we need to do it is to have a Java

    JDK already installed on our system and launch the eclipse IDE after

    extracting the zip file that comes in the download. So, basically what we

    do is the following:

    1. Make sure that JDK and not just JRE is installed on your system.

    2. Unzip the ADT bundle archive that came after being downloaded

    from the Android developer website and place it where you wouldwant your Eclipse and Android SDK directories to reside. Make

    sure you do not change the folder structure, because changing it will

    result in you having to change the Android SDK preferences in the

    ADT plugin for eclipse.

    3. Add the full path to the sdk/platform-tools and sdk/tools subdirectory

    to your PATH variable so that you can access the relevant commands

    from anywhere, otherwise you will need to type in the full path to eachcommand everytime you run it.

    Finally, all you need to do is to launch the eclipse environment and choose

    a default workspace where all your development related files will be stored.

    On existing Eclipse environment

    WindowsThe Windows Android SDK installer

    comes as an executable which

    exposes a wizard like interface which

    checks for dependencies and allows

    you to choose a location to install

    your SDK. Since these are only the

    SDK tools, it will only install thebare minimum packages required

    to start development. You will still

    need to configure this from eclipse

    and download more packages like

    the Android Platform Tools and the

    Android System Image which will

  • 8/13/2019 Digit Devworx March 2013

    19/100

    17GETTING STARTED

    be used for the emulator. You might also need to add the path of the sdk/

    platform-tools and sdk/tools subdirectories to your PATH variable in order

    to use common Android SDK utilities.

    Mac / Linux

    The Mac and Linux SDK comes as a zip file which can be extracted and

    put anywhere you intend to keep it. Finally, as in windows add the sdk/

    platform-tools and sdk/tools subdirectories to your PATH variable with

    the following methods:

    LinuxEdit the ~/.bash_profile or ~/.bashrc files looking for a line that sets the

    PATH variable.

    1. Add the full path location to your $SDK_ROOT/tools location for the

    PATH variable.

    2. If no PATH line exists you can add the line by typing the following:

    3. export PATH=${PATH}:

    Mac

    In the home directory locate the .bash_profile and locating the PATH vari-

    able add the location to your $SDK_ROOT/tools folder.

    Setting up the Eclipse IDENow that everything is set up and the development environment is good to

    go, all that we have left is to procure the Eclipse plugin and install additionalpackages that include the target platform and other APIs after integrating

    it with the exisiting IDE on your system. If you still want to install the IDE

    by yourself, you can do so by getting the Eclipse for Mobile developers

    package at the eclipse.org/mobile/ website which is again available for all

    the three popular platforms. To install the Eclipse ADT plugin, we need

    to add the Google repositories in its Add-On installation dialog. This can

    be done as follows:-

    1. Start Eclipse and navigate to Help > Install new Software.

    2. Click the Add button and name the repository as something like

    Android ADT. The online location for the repository is :

    https://dl-ssl.google.com/android/eclipse/

    3. It will list a couple of available sites, from which you can choose

  • 8/13/2019 Digit Devworx March 2013

    20/100

    18 GETTING STARTED

    Developer tools and check the components you would like to be

    installed in the next screen.

    4. Finally, accept the license agreements and restart eclipse when the

    installation and download is complete.5. When eclipse restart is complete, you will need to set the location

    where you installed your Android SDK. You can do this directly in

    the Welcome to Android window or go to Window > Preferences and

    choose Android on the left, which should show you a field to specify

    the Android SDK location.

    This concludes the configuration of the eclipse development environ-

    ment, following which only additional packages like target platforms andAPIs are left to be installed.

    Target platforms and APIsAs a last step towards environment setup, you must install at least one

    android platform for which you are aiming to target you app. It will be

    used to set up the emulator on which the system image will be used to run

    your application. The ADT bundles the lastest available android platformby default. If you neeed a slightly older version for which you are targeting

    your app, like Android 4.0.4 or Android 4.1 or you had downloaded the

    SDK Tools instead of the bundle, then you will have to download it from

    the Android SDK Manager. To launch Android SDK Manager on Linux or

    Mac, use the android sdk command to launch the Android SDK Manager

    dialog. On Windows, you can launch it after locating the SDK Manager.exe

    file from the SDK directory. Alternatively, it can also be launched from theEclipse IDE itself, by clicking the corresponding Android SDK Manager

    button below the menu bar.

    When you launch the SDK Manager, it should start downloading the

    list of available packages from the server and then show you a list of those

    which are already installed along with the ones which are available. At the

    minimum, make sure you have at least all the Tools packages, one Android

    platform (like Android 4.2) and the Android Support Library installed, tobe able to work sufficiently in your development environment.

    x86 system ImageTargeting your apps for x86 Platform is very easy. You need to select and install

    Android x86 System Image in Android SDK Manager and within couple

    of minutes, your Android x86 System image is up and ready to build apps!

  • 8/13/2019 Digit Devworx March 2013

    21/100

    19GETTING STARTED

    Third party addonsBesides the default addon packages for Android SDK available from Google,

    a number of third party websites might host customized add ons for their

    own specific devices. These can be carriers, manufacturers or softwaredevelopment companies as well. To enable the third party addons you

    need to find a link to the repository.xml file for that particular repository,

    and add them to the SDK Manager. To do this, click on the Tools > Manage

    Add-On Sites. This will show you the Add-On Sites dialog box, where you

    can nd the User dened sites tab. Click on New and add the link to your

    specific repository file. To refresh the list of available packages, click on

    Packages > Reload.

    Creating a new Android Virtual DeviceAn Android Virtual Device stores the configuration for the emulator

    according to which it will do the emulation for your application. By default

    Google provides emulation proles for all the old and new Google Nexus

    devices. Manual configuration can also be done for other devices. Android

    Virtual Devices or AVDs can be created from the AVD manager, whichprovides a decent GUI for conguring and editing the devices.

    The AVD manager can be launched from the Android SDK manager too,

    by clicking on Tools > Manage AVDs. In the AVD Manager screen, click on

  • 8/13/2019 Digit Devworx March 2013

    22/100

    20 GETTING STARTED

    New, which will show a Create new AVD dialog box with various congu-

    rations. It will allow you to name your device and specify the target. For

    example, if you intend to develop for Intel based devices, you would choose

    Intel Atom x86 System Image that you should have installed before. It willfurther ask you for device congurations like size of the SD Card, screen

    size, DPI, RAM size etc. After all this conguration, click on Create AVD

    and you device should be listed on the main screen. You should now be able

    to launch the emulator by clicking on the Start button after selecting the

    device you want to launch.

    Using the Android System EmulatorThe emulator can be controlled easily from the on screen buttons or withthe help of keyboard shortcuts. There are also various commandline

    options to turn on or off specific set of functionality. The keyboard short-

    cuts are quite important and are listed in the table, as referenced from the

    official documentation.

  • 8/13/2019 Digit Devworx March 2013

    23/100

    21GETTING STARTED

    Emulated Device Key Keyboard Key

    Home HOME

    Menu (left softkey) F2 or Page-up button

    Star (right softkey) Shift-F2 or Page Down

    Back ESC

    Call/dial button F3

    Hangup/end call button F4

    Search F5

    Power button F7

    Audio volume up button KEYPAD_PLUS, Ctrl-F5

    Audio volume down button KEYPAD_MINUS, Ctrl-F6

    Camera button Ctrl-KEYPAD_5, Ctrl-F3

    Switch to previous layout orientation

    (for example, portrait, landscape)

    KEYPAD_7, Ctrl-F11

    Switch to next layout orientation

    (for example, portrait, landscape)

    KEYPAD_9, Ctrl-F12

    Toggle cell networking on/off F8

    Toggle code profiling F9

    Toggle fullscreen mode Alt-Enter

    Toggle trackball mode F6

    Enter trackball mode temporarily

    (while key is pressed)

    Delete

    DPad left/up/right/down KEYPAD_4/8/6/2DPad center click KEYPAD_5

    Onion alpha increase/decrease KEYPAD_MULTIPLY(*)

    / KEYPAD_DIVIDE(/)

    Android SDK with IntelliJ IdeaSetting up Android SDK with Android SDK does not require much configu-

    ration after the SDK has been configured as before. The only difference is

    that you need to download the SDK Tools package and manually configure

    it instead on downloading the SDK bundle. Since, IntelliJ Idea supports

    Android app development by default, you don't need to download or install

    anything to enable support, only a little bit of configuration is required. The

  • 8/13/2019 Digit Devworx March 2013

    24/100

    22 GETTING STARTED

    main prerequisite is that you need to have the Java JDK and Android SDK

    configured. Android support in IntelliJ Idea is provided with the Android

    Support plugin that is bundled by default. If however you find that it is

    not available, you can enable it in the plugins configuration wizard or theplugins tab in the settings dialog box.

    The only remaining configuration that remains regarding the Android

    SDK and Java JDK can be done by adding a new Android project or adding

    an Android facet to an existing project. When you do so, the respective

    wizards will automatically ask you to specify the location of the Android

    SDK and Java JDK.

    Android SDK with NetBeans

    The process for configuring Android SDK is also similar with NetBeans.

    Again, the Android SDK and Java JDK obviously need to be set up and

    configured first. The Android app development functionality is provided

    in NetBeans with the help of the nbandroid plugin for Netbeans. To install

    this plugin, following steps need to done :-

    1. Go to Tools > Plugins. Add the update center link for nbandroid to the

    list in the Settings tab : http://kenai.com/projects/nbandroid/downloads/

    download/updatecenter/updates.xml

    2. Now in the Available Plugins tab, install the Android plugin that

    should now be available.

    3. To configure the path of Android SDK, go to Tools > Options > Miscel-

    laneous > Android.4. Mention the location of the Android SDK in the available field.

    You should now be able to easily create new Android projects and

    applications.

    Optionally you can also install the plugin manually by installing it from

    a downloadable zip file. This can be done as follows :-

    1. Download the plugin from the nbandroid website : http://kenai.com/

    projects/nbandroid/downloads2. Unzip the fle and go to Tools > Plugins > Downloaded

    3. Click on Add plugins and select those which match the vsersion of

    your current IDE.

    4. Click on the Install button, which will ask you to accept the licenses

    after which installation will begin.

    It should be noted that Android development with other IDEs is rec-

  • 8/13/2019 Digit Devworx March 2013

    25/100

    23GETTING STARTED

    ommended only when you are accustomed to their interface or already

    use them on your system. If you are a new Android developer, the official

    eclipse plugins are more than enough and will get better community sup-

    port if you face any problems with the plugin or during the process ofyour development.

    Android SDK in Other Linux DistributionsTo give you an example of setting up a development environment in other

    Linux Distributions, it is sometimes much easier to get the SDK from the

    official repositories which provide it in the form of a preconfigured package.

    Arch Linux

    Arch Linux, for example provides two AUR (Arch User Repository) packages

    by the name of android-sdk and android-sdk-platform-tools. The process

    for installing these AUR packages is as usual and these provide access to

    the Android SDK quite easily. If you want to use eclipse as you development

    environment, a package called eclipse-android is also available.

    Intel Hardware Accelerated Execution ManagerIntel Hardware Accelerated Execution Manager is a hypervisor (or a Virtual

    Machine Manager) that greatly speeds up the execution of the commands

    in the emulator. Intel claims that it does this by almost 5 to 10 times the

    performance of an emulator without the presence of HAXM. The sur-

    prising fact is that it is actually true and apps are noticebly much faster

    and even NDK based games and resnderscript based heavy computationsare supported which suddenly become much more smoother to run and

    thankfully no longer require a real development device to be bought for

    testing and development purposes. The result is that it not only saves time,

    but also a lot of money.

    HAXM works on Intel-VT enabled processors and is supported on all

    the three platforms namely Windows, Mac OS X and Linux as long as

    they are on Intel processors and use the Intel Atom X86 System Image. Ituses the hardware virtualization features built into the Intel processors,

    as opposed to much slower software based emulation, where most of the

    virtualization is done at the hardware level on the host processor. It even

    supports GPU emulation (since SDK release 17), so that OpenGL calls can

    be executed on the host. Imagine the amount of graphics performance that

  • 8/13/2019 Digit Devworx March 2013

    26/100

    24 GETTING STARTED

    is enhanced by this very functionality, where only the peripheral emulation

    is left to be handled by the software.

    The installation of Hardware Accelerated Execution Manager requires

    the following minimum system requirements:

    Intel processor with VT support

    1 GB RAM

    (Mac OX 10.6 Snow Leopard / 10.7 Lion) / (Microsoft Windows 7, Vista,

    XP SP2 32 bit) / (Ubuntu Linux 64 bit recommended)

    Android SDK

    Android X86 System Image JDK

    All the above system requirements are checked by the HAXM installer,

    which if not met, makes the installation to be failed. To check if your processor

    is supported or includes the VT technology, you can check the system BIOS

    or refer to the Intel website.

    To install HAXM, it can be procured directly from the Intel website or

    from within the Android SDK Manager itself from under the Availablepackages below extras folder.

    Getting Intel HAXM from the Android SDK

    1. Start the Android SDK manager with the android sdk command.

    2. Go to Extras and check the Intel x86 Emulator Accelerator (HAXM)

    entry.

    3. Click the Install button.4. Review License Agreement and Accept it, followed by which you need

    to click Install Again.

    5. The Installer will be downloaded to the tools directory under the Android

    SDK folder from where it can be run to continue the installation.

    Installation of Intel HAXM on Windows

    1. Run the Installer that you downloaded from the Intel Website or fromthe Android SDK Manager.

    2. Accept the License Agreement and Click Next.

    3. The Installation Wizard will ask you to allocate the amount of RAM you

    want to use for HAXM. By default this setting is 1024, if you want to use

    more than 2048, it is recommended that you only use a 64 bit system.

    4. When the Installation is finished, go to command prompt and check if

  • 8/13/2019 Digit Devworx March 2013

    27/100

    25GETTING STARTED

    it is running by typing the command sc query intelhaxm. This should

    show you a status as Running, if not then try starting it and if you face

    any errors, try reinstalling the whole software.

    5. Additionally you may see some errors regarding Intel XD or Intel

    VT-x not being enabled, in which case, you will need to go into the

    BIOS and enable this setting. If the installer says that either of thesesettings is not supported by your processor, then you will not be able

    to use this software.

    Installation of Intel HAXM on Mac OS X

    Installation of Intel HAXM on Mac OS X is similar to Windows with the

    help of the Installation wizard where you will need to specify the amount

    of memory to be allocated. To check if HAXM is running, you can run thekextstat | grep intelcommand which should show you the kernel extension

    named com.intel.kext.intelhaxm to be loaded in memory.

    Installation of Intel HAXM on Ubuntu

    Ubuntu Linux is one of the main platforms on which a lot of developers

    use Eclipse and AVD to work on building their Android applications. A

    From the Android package manager, install Intel Hardware Accelerated Execution Manager

  • 8/13/2019 Digit Devworx March 2013

    28/100

    26 GETTING STARTED

    lot of build servers are also based on Linux and hence it is very important

    for Intel to support Hardware Assisted KVM Virtualization in a manner

    similar to HAXM on Windows and Mac. The following KVM installation

    instructions can also be referred from the Ubuntu Community documenta-

    tion page for KVM.

    Installing KVM1. The first task is to check for prerequisites and see if the required

    configurations are indeed suppoted on your system. So, to check if

    your processor supports hardware virtualization, run the following

    command : egrep -c '(vmx|svm)' /proc/cpuinfo

    If the output value turns out to be zero then your processor does not

    support hardware virtualization and if it somehow turns out to be greater

    than that, you are good to go!

    2. To check if KVM is suppported on our system, we need to install the

    CPU checker utility, with the help of the following command: -

    sudo apt-get install cpu-checkerWhen this is done, you will be able run the kvm-ok command to see if

    KVM is supported.

    3. Finally, if you want to allocate more than 2GB RAM to a VM, then it

    is required that you have a 64 bit system. To check for that, run the

    following commands:

    egrep -c ' lm ' /proc/cpuinfo

    If the output is 1, then it means that you are running a 64 bit system. Inorder to make sure that you are also running the 64 bit kernel currently,

    you can run uname -m command to check for the architecture.

    4. To get started with the installation, the required packages can be

    installed from the repository as follows:

    sudo apt-get install qemu-kvm libvirt-bin ubuntu-

    vm-builder bridge-utils

    5. It will ask for postfix configuration during the install process, whichyou can ignore by choosing the No Conguration option.

    6. To start using the KVM virtualization, you need to add the user that

    will be running the software to the kvm and libvirtd groups.

    7. Log out and Log in again to make the changes effective.

    8. To see if everything has been set up, check the output of

    sudo virsh -c qemu:///system list.

  • 8/13/2019 Digit Devworx March 2013

    29/100

    27GETTING STARTED

    9. To start the emulator from the commandline, you can execute:

    emulator-x86 -avd Your _ AVD _ Name -qemu -m 2047

    -enable-kvm

    10. Alternatively, to use it from eclipse you will have to change the RunCongurations for the Android Application Project. There you will

    have to choose the x86 based AVD that needs to be run as the target

    and in Additional commandline options, you will have to specify the

    following:-qemu -m 2047 -enable-kvm

  • 8/13/2019 Digit Devworx March 2013

    30/100

    28

    CHAPTER 3

    Developing forAndroid

    GIVEN THE RISE of Android in the Indian market, andthe variety of mobile devices, an app's availability on the

    Google Play Store gives it immense visibility. With this advan-

    tage comes another challenge--that of customisation.

  • 8/13/2019 Digit Devworx March 2013

    31/100

    29DEVELOPING FOR ANDROID

    The Android building blocksAfter installing the SDK, the first major task is to understand the basic

    building blocks that make Android up. Once we've gotten familiar with

    the basic building blocks of Android we will write a simple Androidapplication to illustrate how to use them in a rather practical setup.

    The basic Android building blocks are:

    Activities

    Intents

    Views

    Content providers Services

    Notifications

    Android manifest

    Before we proceed to building an app, let's go through each

    building block and understand what role they play in the life of an

    Android application.

    Activity

    An activity is a core building block and is at the heart of most Android

    applications out there. To put it simply, an activity is what you see on

    a screen in Android. Users can interact with this screen to accomplish

    a particular task.

    As an example, consider the dialerscreen as an Activity. Whenever a user

    wants to dial a number and make a call, he/

    she must use the dialer 'Activity' or screen

    to enter the number.

    While the user inputs the digits to be

    dialled, each activity is given a window

    in which to draw its user interface and adeveloper can specify how he/she wants

    the activity to look.

    As you might guess, an Android appli-

    cation might have multiple screens and

    therefore might contain multiple activi-

    ties. For example, a dialer application

  • 8/13/2019 Digit Devworx March 2013

    32/100

    30 DEVELOPING FOR ANDROID

    might have an Activity where you enter

    the number to be dialed, once you hit 'dial'

    it might invoke another Activity that shows

    the number which is being dialed and so on.So, applications typically have multiple

    Activities in Android and the activity which

    is presented to the user when launching the

    application for the first time is called the

    'Main' Activity.

    An Activity also has a lifecycle of its

    own and at some point in the same lifecyclethe Activity is created, started, paused,

    stopped and eventually destroyed.

    In other words, when the screen is

    shown on the screen - in developer termi-

    nology, it comes to the foreground - the Activity is 'created' and then

    'started'. So any basic setup for the activity is done in the onCreate

    method, which is called when the Activity is getting created beforebeing shown on the screen, typically, you would be setting up the User

    Interface of the Activity here. Similarly, there are similar methods/call-

    backs like onStart, onResume, onPause, onStop and onDestroy which

    are called when the Activity is being started, resumed, paused, stopped

    or destroyed respectively.

    A quick note here, an activity which is in the foreground (directly

    Source: android.google.com http://dvwx.in/Y0mCh9

  • 8/13/2019 Digit Devworx March 2013

    33/100

    31DEVELOPING FOR ANDROID

    visible on the phone) is said to be in an 'Active' state and is able to

    perform operations, as soon as the user starts another Activity, the old

    Activity is 'paused' and stopped and then 'pushed' on a stack called the

    'Activity stack'. In this state, the activity is no longer able to performany operations. If the user goes back from the new Activity to the old

    Activity, the old Activity is then 'popped' from the Activity stack and

    then 'started' and 'resumed' to go back to normal operation.

    Intent

    As mentioned previously, there might be multiple Activities in an

    Android application and we might need to move between them. An Intentis a mechanism by which we can move between Activities or between

    other Android building blocks such as Services. More on that later.

    Let's take the example of the dialer application again, when you are in

    the Android home screen, you are basically in the home screen Activity,

    here when you click the dialer button, you use an 'Intent' to launch the

    dialer application 'Activity'. There you enter the phone number that

    you want to dial and hit the dial button which uses another 'Intent' tolaunch the dialing 'Activity'.

    You can also pass data in an Intent, for example, when you enter the

    phone number of a person in the dialer and hit dial, you might want to

    pass the phone number as a parameter to the next Activity and you can

    pass that using the Intent itself.

    ViewsViews are the basic User Interface building blocks in Android and an

    Activity is typically made of many such atomic 'Views'.

    Simply put these 'Views' know how to draw themselves on the screen

    and they respond to user events like a click or a long press. Example of

    Views in Android are TextViews which show simple text on the screen,

    ImageViews which draw images on the screen, EditText which let users

    enter text and so on.Views are also hierarchically arranged in the form of trees to draw

    fairly complex user interface layouts. For example, here in the twitter

    app, 4 ImageViews (the Twitter logo, the refresh button, the tweet button

    and the search button) are arranged linearly to form one atomic element

    called the 'ViewGroup'. Since we arranged all the elements linearly (in

    a straight line) we call it a LinearLayout ViewGroup.

  • 8/13/2019 Digit Devworx March 2013

    34/100

    32 DEVELOPING FOR ANDROID

    Similarly if you look a tweet row in the twitter app, the various Text-

    Views and ImageViews are arranged in a row to form another ViewGroup.The idea is that we can arrange all these individual Views together in

    a way that makes sense to the user and all Android applications group

    views together to make very complex layouts like the one shown in the

    twitter app.

    Also note that the layout which specifies the arrangement of the

  • 8/13/2019 Digit Devworx March 2013

    35/100

    33DEVELOPING FOR ANDROID

    individual views is typically mentioned in a separate xml file. Defining

    the layout in an xml file enables Android to conform to the Model View

    Controller architecture pattern and helps separate the User Interface

    component from the actual code.

    Content Providers

    As you might know databases are used to store and retrieve information

    and Android provides an inbuilt database called SQLite to achieve that

    functionality. It also provides an additional functionality called 'Content

    Provider' to enhance the functionality of a database in a mobile scenario.

    So a Content Provider is a wrapper on a database that provides

    additional functionality to share data with multiple applications and

    to manage data security with respect to the same. Let me illustrate that

    with an example.

    Let us say there is a contact application that does contact management

    on an Android phone. As discussed before, that application might have

    multiple Activities within it, like an Activity to add a contact, anotherActivity to view all the contacts, another one to Edit a contact and so on.

    When you add a contact, instead of directly asking the database to add

    a row for the contact, you would ask the 'Content Provider' to add that

    row for you. The Content Provider would then have the logic of knowing

    where to store the row, in the database, in a file or even in the cloud.

    Now say there is another application, say an sms/text app which

  • 8/13/2019 Digit Devworx March 2013

    36/100

    34 DEVELOPING FOR ANDROID

    needs access to a persons phone number. Now under normal circum-

    stances, getting access to that data would be a cumbersome job (sharing

    a database is not always straightforward) but thanks to the ContentPro-

    vider which makes data sharing easy, we can do that in a flash. So whenthe sms app needs access to the phone number, it queries the contacts

    'ContentProvider' which in turn knows where the data is stored and

    where it should look. Once the query is complete, it then returns the

    results back to the sms application. This provides a very simple and

    straightforward approach to sharing data between multiple applications

    while maintaining security.

    Services

    You might recall that while discussing Activities, we saw how Activi-

    ties are 'paused' and 'stopped' when they go into the background. You

    might think that this might be a problem for applications that need tokeep working in the background for a long time, like a music player or

    a download application. Apps like that might have a tough time per-

    forming while in the background and need a way to keep playing music

    or continue downloading even when they are not in the foreground.

    For such functionality, a 'Service' should be used. In other words, a

    Service is a faceless task that runs in the background and has no user

    How it all comes together...

  • 8/13/2019 Digit Devworx March 2013

    37/100

    35DEVELOPING FOR ANDROID

    interface. You can enable it to run for a specific amount of time and do a

    certain task. Any task which should be done even if the corresponding

    Activity might be pushed to the background should be delegated to

    a Service.Now that you are slowly understanding the basic building blocks of

    Android, you are starting to get a picture of how Android applications

    are built, they are often a combination of all such blocks, like an app

    typically has multiple Activities, many Views, maybe a ContentProvider

    and maybe even a Service, all depending on the use case

    NotificationsNotifications are one of the hallmark features of Android. They notify

    users about events and provide visual, audio or vibration feedback. In

    the newer versions of Android, you can even empower users to provide

    action on the notification.

    For example, in this recording application, while playing back a

    recording, you can enable users to pause the playback or skip to the

    next track from within the notification itself.

    Android manifest

    The final basic building block of Android is the Android manifest file.

    This file provides critical metadata about your application, like the

    package name for your app, the various components like Activities,

    Services etc. in your app, the permissions that your app might seek

    (example: your app needs to seek the 'INTERNET' permission to be ableto access the internet), the libraries that your app uses, the version of

    Android you support and so on.

    It is a very important building block as the appearance and function-

    ality of the whole application depends on the declarations you make in

    the manifest file.

    A simple applicationNow that we've gone through the basic building blocks of Android, we'llsee how we can harness the same building blocks to create a simple

    music player program in Android.

    The application is intended to be really simple and will provide

    functionality to play, pause and stop a predefined music file. Again,

    to keep things simple, the UI is expected to look something like this:

  • 8/13/2019 Digit Devworx March 2013

    38/100

    36 DEVELOPING FOR ANDROID

    To create a new program, go to File>New>Android Application Project

    In that screen, enter the name

    of the application say Simple

    Music PlayerAs you might have noticed, as you

    enter the name of the application, the

    project and package name for the app

    start populating automatically.

    The package name is typically in

    the format of com..There are some other variables

    that are filled by default, like the

    minimum required sdk, target sdk

    etc. which let us specify the version

    of Android we are targeting but let

    us not look at them right now, just

    click next.Hit next on the next screen.On the next screen, you can select

    the launcher icon for your applica-

    tion, you can play around with the

    launcher icon for your application, for

    now, just leave everything at its default value and hit next.

    The next screen in the wizard highlights what kind of 'Activity' is

    created in your application by default. Since we are making a simpleapplication, just hit Next. The final screen is about the name of the

    Activity created by default and the name of the file that specifies the

    layout (remember the separate xml file we discussed before), for now,

    lets again leave everything to their default values and hit Finish.

    Once you hit finish, you are taken to the UI editor which previews

    how your application looks by default. As you can see, the default

    application has a View which shows 'Hello World' in the centre of theapp, this is the UI visual editor in Android.

    Now let's get started with the User Interface design of the applica-

    tion, to begin, click on the 'hello world' TextView at the centre of the

    screen and hit Delete.

    Next, as we need three buttons in the application, let us drag and

    drop three buttons from the "Form Widgets" section of the Palette on the

    Example of a content provider app

  • 8/13/2019 Digit Devworx March 2013

    39/100

    37DEVELOPING FOR ANDROID

    left to the top left of the Android

    screen like so:

    Drag all the three buttons in a

    straight line so that it appears asseen the image below:

    Next click on 'activity_main.

    xml' at the bottom to view the

    underlying xml code that gener-

    ates this layout. It is very impor-

    tant to know how these layouts

    are generated as understand themwill help you design even more

    complex layouts.

    Here you can see that there

    is a 'RelativeLayout' element at

    the very start which contains 3

    'Button' elements inside it. We

    shall cover the RelativeLayoutViewGroup in a later chapter, but

    here it is important to understand

    that the RelativeLayout ViewGroup specifies how the child elements

    (each button) is arranged on the screen.

    Note that each child/button has a

    number of different attributes, the first

    of which is an id, followed by others.Let us quickly describe some of them.

    The android:id attribute identifies

    the element in the xml file and can be

    used to reference the same from within

    the code, for example, the id for the

    first button is '@+id/button1' which

    translates to the following: the firstbutton should create a new id with an

    id of 'button1'. So in code, whenever

    we need to reference this button, say

    we want to know when it was clicked,

    we will need to use the id of 'button1'.

    The android:layout_width and

    A sample music player app

    Buttons in the app

  • 8/13/2019 Digit Devworx March 2013

    40/100

    38 DEVELOPING FOR ANDROID

    android:layout_height attributes highlight the width and height of

    the element respectively. Here we say that the width and height of the

    button should be 'wrapped' to the width and height of the content in the

    element, in other words, in case the text in the button should increase,

    the length of the button would increase automatically.

    The android:text attribute highlights the label of the button, let us

    To begin your Android project, go to File > New

    Enter the name of your application

  • 8/13/2019 Digit Devworx March 2013

    41/100

    39DEVELOPING FOR ANDROID

    change that to Play, Pause and Stop for each of the buttons and hit Save(Control + S/Command + S).

    Hit the Graphical Layout tab and see how the labels of the buttons

    have changed to reflect the changes in the android:text attribute.

    In the next step, you'll have to select the type of activity

    After you enter your application name, you need to configure its icons

  • 8/13/2019 Digit Devworx March 2013

    42/100

    40 DEVELOPING FOR ANDROID

    Folder structureNow that we've started working on the look of the application, the next

    step is to get familiar with the rest of the application. Notice the package

    explorer section to the left of the eclipse window, that window displays

    The last wizard screen

    Once you're done, you'll see the layout of your app as it stands

  • 8/13/2019 Digit Devworx March 2013

    43/100

    41DEVELOPING FOR ANDROID

    a list of the folders that make up your application. Let us go throughthose folders one by one.

    The first folder on the left is called 'src', as the name suggest, it

    contains the source code of your application. Program code such as

    Three buttons in a line (outline 'activity_main.xml' in a circle)

    Drag and drop buttons as you need

  • 8/13/2019 Digit Devworx March 2013

    44/100

    42 DEVELOPING FOR ANDROID

    MainActivity.java resides in this folder. As you can see, individual java

    source files are arranged under their respective package names. Double

    clicking on a file (like MainActivity.java) will open it in the central edit

    area of Eclipse, it is there that you will be spending most of your time.

    Lets take a quick detour here and check out a folder called 'res'. This

    Set the text within activity_main

    Acitivity_main.xml

  • 8/13/2019 Digit Devworx March 2013

    45/100

    43DEVELOPING FOR ANDROID

    folder represents the list of resources used

    in your application. Resources can be of

    many types, images/vectors or 'drawables'

    as they are called in Android are one type,layouts like the one that was created by

    default is of another type, Android menu's

    (the things that pop up when you press

    the menu/settings button your phone) are

    of another type. Even layout styles and

    external strings are considered resources

    in Android and can be stored under theirrespective folder in this directory.

    Note how there are multiple folders

    which begin with 'drawable' here called

    drawable-hdpi, drawable-ldpi, drawable-

    mdpi and drawable-xhdpi. DPI in HDPI

    stands for dots per inch and the H, M, L

    and XH stand for High, Medium, Low and Extra High respectively andthey represent the screen densities of devices that users might have. A

    galaxy nexus which has more than 300 dots per inch falls under the

    xhdpi category whereas the nexus s which has a lower pixel density falls

    under the hdpi category. The idea here is to store different resolutions

    of the same image in different folders so that Android can automati-

    cally select which is the best image for the users phone at run time. So

    for example, you might store a very high resolution image in the xhdpifolder and store a lower resolution version of the same in hdpi and then

    a lower one in mdpi and so on.

    Note that in addition to pixel density you can attach many other such

    qualifiers to the folder name to specify how Android chooses resources

    at run time. For example you can choose a specific resource if the phone

    is in portrait mode and another when you are in landscape mode. More

    of that is available in this link: http://developer.android.com/guide/practices/screens_support.html

    Moving on, the next folder is called 'gen', this folder contains files that

    are automatically generated by Android and should never be tampered

    with. The file R.java is of particular importance, basically whenever

    you add a resource like a new layout, a View etc. in an app, Android

    automatically catalogues it for you in this file. This is done so that

    The folder structure

  • 8/13/2019 Digit Devworx March 2013

    46/100

    44 DEVELOPING FOR ANDROID

    you can easily refer to it in your program

    without any manual intervention. See how

    different drawables, layouts, menus, strings

    and all other resources are given an identi-fier here under all the different classes. Our

    activity_main.xml file here is represented by

    the int activity_main in the class layout, which

    translates to R.layout.acitivity_main

    So say you create a new layout called new-

    layout.xml in your application, thanks to this

    automatic catalogue, you would then be ableto refer to it as R.layout.newlayout

    Next we see some of the libraries that

    are used in the application. We can see the

    Android 4.2 and some other Android depend-

    encies that is used to compile the app. The

    next folder is the assets folder where you can store raw assets.

    Next we have the bin folder which is the output directory of thebuild of the Android app. Here you would find the final apk file for your

    application after a build is complete. Finally we have the libs folder,

    where you can store private or 3rd party libraries.

  • 8/13/2019 Digit Devworx March 2013

    47/100

    45DEVELOPING FOR ANDROID

    There are also other files like AndroidManifest.xml which we have

    discussed before.

    Now that we have understood the basic directory structure of an

    Android apps, let us get back to our app. Remember that we havedesigned the basic look of our application, the next step is to go into

    code and find out when a button has been clicked. To do that, first click

    on the MainActivity.java file under your respective package name.

    This file represents the 'main' or first activity of your application

    and this is the activity that is launched when your app is launched. Also

    note that there are some pre-created methods for you. The first one is

    onCreate and that is what we're really interested in.As discussed before, an Android activity has its own lifecycle, it

    is created, started, paused and so on. Along the same lines, when the

    activity is first created, the onCreate method is called and this is where

    you should do a lot of Activity initialisation jobs. Notice how there

    is a statement called setContentView(R.layout.activity_main) in this

    method, this tells Android that when the activity is created, set the view

    of the application to what is represented by R.layout.activity_main.In other words, whenever the application is started, the layout inside

    activity_main.xml will be shown on the screen.

    Our first task here is to find out when a button is clicked, more

    specifically, when the play, pause and stop buttons are clicked. So we

    need to get a reference to the buttons and then set listeners (remember

    Java listeners) on them.

    To create a reference to the play button we need to write the fol-lowing statement

    Button playButton = (Button) fndViewById(R.

    id.button1);

    This statement basically tries to get a reference to the button by using

    the id of the button which is 'R.id.button1' on the method findViewById.

    The method findViewById returns a generic View object which we must

    typecast to 'Button' to get a proper button reference.Note how you might get an error in the form of a red underline under

    'Button'. If you hover over button you will find that it states "Button

    cannot be resolved to a type" which basically means that it needs to

    import a package in order to understand what 'Button' is. If you hover

    over button, you will also find that Android has offered you with around

    7 quick fixes, the first of which is to "Import Button (android.widget).

  • 8/13/2019 Digit Devworx March 2013

    48/100

    46 DEVELOPING FOR ANDROID

    When you click that Android automatically imports the necessary

    package so that you don't have to manually do it. Do that and you will

    see that the errors have disappeared, there are still a couple of warnings

    but lets ignore them for now.Write a similar statement to get references to the other buttons like so:

    Button pauseButton = (Button) fndViewById(R.

    id.button2);

    Button stopButton = (Button) fndViewById(R.

    id.button3);

    Once you do that, the next step is to attach 'onClickListeners' to these

    buttons so that they you are informed as soon as the buttons are clicked.

    To do that take the first button and then type the following

    playButton.setOnClickListener()

    inside the brackets we need to create an anonymous inner class forthe listener, to do that type new and then press control + enter to let

    autocomplete take over. Select the first option which is View.OnClick-

    Listener and hit enter.

    The code should look something like this:

    playButton.setOnClickListener(new OnClickListener() {

    @Override

    public void onClick(View v) {

    // TODO Auto-generated

    method stub

    }

    });

    Remember to put a semi colon at the end and hover over the OnClick-

    Listener in new OnClickListener() to import the necessary package.

    Notice how all the errors have magically disappeared. The idea here is

    that as soon as the play button is clicked, the method onClick inside

    that new OnClickListener is called. Over there we can do our processing.

    For now we'll show a short message called 'Toast' here.

  • 8/13/2019 Digit Devworx March 2013

    49/100

    47DEVELOPING FOR ANDROID

    Toast.makeText(MainActivity.this, "Starting to play",

    Toast.LENGTH_SHORT).show();

    This line will enable us to show a short message: "Starting to play"on the screen. Now let us try this on the emulator, run this program by

    right clicking on the program name in the package explorer, then select

    Run As and then select 1. Android application. See how a short message

    is shown on the screen as you press play.

    Now let us attach similar listeners for the other buttons, like so

    pauseButton.setOnClickListener(new OnClick-Listener() {

    @Override

    public void onClick(View v) {

    // TODO Auto-generated

    method stub

    Toast.

    makeText(MainActivity.this, "Pausing", Toast.LENGTH_

    SHORT).show();

    }

    });

    stopButton.setOnClickListener(new OnClickLis-

    tener() {

    @Override

    public void onClick(View v) {

    // TODO Auto-generated

    method stub

    Toast.makeText(MainActivity.this, "Stopping", Toast.

    LENGTH_SHORT).show();

    }

    });

    Now every time you press the Pause or Stop buttons, you get a similar

    message. Now that we know when the buttons are clicked, we need to

    understand what we might do when we click them.

    For this we need to copy the music that we want to play to a new

    folder under resources. Lets begin by creating that folder, right click

  • 8/13/2019 Digit Devworx March 2013

    50/100

    48 DEVELOPING FOR ANDROID

    on 'res' in the Package Explorer and then select Create new > Folder.

    Over there type 'raw' as the folder name. See how the folder pops up

    under the res folder.

    Next, select the music file you want and rename it to somethingsimple, like a.mp3 (note, you might face some difficulty with complex

    names and upper case characters, so rename it to something really simple

    like a.mp3) and then drag and drop the file to the raw folder in eclipse.

    You will be asked to Copy the file and then hit Okay. Notice how the

    file now appears in the raw folder.

    Next to play that object we need to create a MediaPlayer object, so

    to do that declare the following as a Class variable (just under publicclass MainActivity extends Activity { )

    MediaPlayer mMediaPlayer;

    Then initialise it in in onCreate, preferable just before you get a

    reference to those buttons but after setContentView.

    mMediaPlayer = MediaPlayer.create(this, R.raw.a);

    Here we are creating a new MediaPlayer object and using the a.mp3

  • 8/13/2019 Digit Devworx March 2013

    51/100

    49DEVELOPING FOR ANDROID

    file we copied in the raw folder to initialise it.

    Now that we have initialised the object, we need to start playing it

    when we click the playButton. To do that we need to inside the onClick

    method of the OnClickListener for the play button and write the fol-lowing:

    mMediaPlayer.start();

    This tells Android to start playing the music.

    Similarly to pause and stop the music add the following inside the

    onClick method of the listeners for the pause and stop buttons respec-tively like so:

    inside the pause button listener:

    mMediaPlayer.pause();

    inside the stop button listener

    mMediaPlayer.stop();

    There you are all set, save the program and run it. Hit play and there,

    you can start listening to the music file. In case you are not able to hear

    anything, make sure to un-mute your speakers :D

    Notice how pause and stop work great as well, also note how you

  • 8/13/2019 Digit Devworx March 2013

    52/100

    50 DEVELOPING FOR ANDROID

    can play after pausing a file right out of the box.

    So here we looked at how we used the basic Android concepts to

    create a simple program where we were able to play pause and stop

    playing music in almost no time.

    Developing for Android

    Interested to learn more about Android x86 Development Platform then visit

    below links:

    Register at Intel Android Developer Zone to get latest information

    about Android on x86:

    http://software.intel.com/en-us/android

    Coding Android Game App to support Intel x86? Here are some examples:

    http://software.intel.com/en-us/articles/coding-android-game-app-to-sup-

    port-intel-x86-here-are-some-samples

    Creating and Porting NDK based Android Apps on Intel Architecture:

    http://software.intel.com/en-us/articles/intel-for-android-developers-learn-

    ing-series-7-creating-and-porting-ndk-based-android

  • 8/13/2019 Digit Devworx March 2013

    53/100

    CHAPTER 4

    GUI DevelopmentTHE USER INTERFACE (UI) on the Android platform has changed

    drastically over the past few years. It went from being a conservatively

    designed platform to something that was really modern and beautiful.Given the heightened focus on UI design and the look and feel of the

    app, it's critical to get UI design right. Keeping that in mind, let's look at

    the fundamental building block of user interfaces in Android.

  • 8/13/2019 Digit Devworx March 2013

    54/100

    52 GUI DEVELOPMENT

    Views

    As discussed Views are the foundational user interface elements in

    Android. In the previous chapter, we had created a particular ViewButton

    and here we shall take a look at more such views.TextView is one of the most basic View elements in Android and

    represents a display of text on the screen.

    EditText is a similar control but one where you can edit or enter text.

    A Button, as the name suggests, is a control which allows users to

    press or click it. Similarly, a CheckBox is a two-state button that can

    either be in a checked or unchecked state. A RadioButton is similar to

    a Checkbox; but unlike a CheckBox, once a RadioButton is checked, itcannot be unchecked.

    A Spinner is the equivalent of a DropDown menu in forms, it can

    have many options and the user can select one amongst them.

    Now there are two basic ways of creating/displaying a view, one in

    XML and the other one in code. Let's look at how we can do both.

    The first way of defining a View is in XML, this way this conforms

    to the Model View Controller architecture and separates the Viewdefinition and declaration in a separate area.

    In this case, to define a TextView we need to create a TextView ele-

    ment as follows:

  • 8/13/2019 Digit Devworx March 2013

    55/100

    53GUI DEVELOPMENT

    android:layout _ width="wrap _ content"

    android:layout _ height="wrap _ content"

    android:text="This is a text box" />

    Here the TextViewelements has many

    attributes, the android:id

    attribute assigns a unique

    id to this TextView,

    the layout_width and

    layout_height attributes

    specify the width andheight of the element, in

    this case, "wrap_content"

    means that the TextView

    will adjust its width and

    height based on its con-

    tent. Finally the text con-

    tent of the TextView is specified by the android:text attribute.In a similar way, one can create similar elements for EditTexts, But-

    tons and other Android Views. The second way of declaring/defining

    a View is through code, as follows:

    TextView tv = new TextView(this)

    Although this is not the primary way of defining a UI in Android,

    at times it is very handy as you might want to add, update or remove

    views dynamically.

    Events

    Just like Java, in Android user interactions like a click, long click etc. are

    classified as events and we can intercept events generated by Android

    by using EventListeners. For example, one of the most commonly used

    EventListener is the onClick() event listener and this is called whenever

    a View (like a Button, TextView etc.) is clicked.Similarly the onLongClick() event listener is called whenever a user

    touches and holds a View.

    As seen in the previous chapter, we can create an OnClickListener

    and attach it to a button to receive callbacks on these events. For example

    Button playButton = (Button) fndViewById(R.

    id.button1);

  • 8/13/2019 Digit Devworx March 2013

    56/100

    54 GUI DEVELOPMENT

    playButton.setOnClickListener(new OnClickListener() {

    @Override

    public void onClick(View v) {

    // TODO Auto-generated

    method stub

    Toast.

    makeText(MainActivity.this, "Starting to play", Toast.

    LENGTH _ SHORT).show();

    mMediaPlayer.start();

    }

    });

    LayoutsNext, lets have a look at Layouts. Layouts define the overall structure

    of the User Interface and define how individual Views like TextView,

    EditText and the like are placed in the overall User interface of the

    application. So layouts are primarily a group of Views and are formed

    from the 'ViewGroup' class.Now there are a lot of different subclasses of ViewGroup and each

    of them provides a very different way of displaying the Views in them.

    While on the subject of Views, let's consider them. What follows is a

    list of the most popular Views.

    Add text to your app

  • 8/13/2019 Digit Devworx March 2013

    57/100

    55GUI DEVELOPMENT

    LinearLayout

    A LinearLayout is a layout where the children are arranged in a single

    horizontal or vertical row. So for example, if you want TextView, an

    EditText, an ImageView and a Button is a straight t vertical line, wecan use a LinearLayout as follows:

    Here we have defined a Vertical LinearLayout where each of thechildren either has the width of its parent or has a width that depends

    on its content.

    RelativeLayout

    Next, lets have a look at a RelativeLayout. Here the location of chil-

    dren are defined relative to each other or relative to their parent. Take

  • 8/13/2019 Digit Devworx March 2013

    58/100

    56 GUI DEVELOPMENT

    this for example:

    Here we have a TextView at the top of the page and a button at the

    bottom of the page. THe ImageView is put at the top of the button (at

    the bottom of the page) and aligned to the left of the page. The EditText

    is put above the Button but to the right of the ImageView.

  • 8/13/2019 Digit Devworx March 2013

    59/100

    57GUI DEVELOPMENT

    Such complex UI structures can be created really easily in a Rela-

    tive layout and this is without doubt one of the most powerful layouts

    out there. The code above will generate an app that resembles the fol-

    lowing image:

    FrameLayout

    Next lets look at FrameLayout, a FrameLayout is a layout where all the

    child views are anchored to the top left of the parent by default and

    where you would want the Views to overlap each other. You can howeverchange the position of the children within the parent by controlling the

    android:layout_gravity attribute. A good use case of a FrameLayout is

    to write a label on an Image.

  • 8/13/2019 Digit Devworx March 2013

    60/100

    58 GUI DEVELOPMENT

    android:src="@drawable/sampleimage"

    />

    Here we have an ImageView anchored to the FrameLayout and then

    we have a TextView which is used to label the Image at the bottom,

    center position of the image.

    ListView

    Next, lets look at some complex UI elements, the first of which is the

    ListView. A ListView is a ViewGroup that contains a list of scrollableViews that are created dynamically by taking data from a data source

    Suggested pattern for List View. Source: developer.android.com

  • 8/13/2019 Digit Devworx March 2013

    61/100

    59GUI DEVELOPMENT

    like a database, array etc.

    Let's take an example of a Twitter application, here you might have

    stored all the tweets, user data, location of the tweet in a database and

    to show the tweet, you would need to display this data dynamicallyfrom the database. As you keep on adding data in the database, you

    want them to be automatically visible to user without having to add

    each row manually.

    That is where you can use a ListView and another structure called

    an Adapter. An Adapter is an object that takes a row of data from the

    database/array etc and creates a 'View' for that row in the ListView.

    So the Adapter is responsible for gathering the necessary informationabout a tweet from the database and then structuring in such a way

    that it looks like a tweet.

    As you go down a ListView, the Adapter automatically gathers

    more data in the database and displays them in the ListView while

    reusing Views at the top that became invisible when the ListView was

    scrolled down.

    GridView

    A GridView is very similar to a ListView but the main difference is that

    the list is just not a single vertical list but a two dimensional list of items.

    For example, to create an image gallery you can have a two dimensional

    list of elements backed by a GridView. Just like a ListView, a GridView is

    backed by an adapter which fetches the data from a database or array etc.

    Menu

    Menus are common UI elements in Android, they can refer to the

    menu you see when you press the Options button on your Android

    phone or when you click on menu options in the Action Bar at the top

    of applications.

    There are also can be contextual or popup menus which appear when

    you long press on an item.

    Dialogs

    A dialog is a window that allows the user to enter some information or

    to make a decision, typically dialogs prompt the user to make a deci-

    sions but at times a Dialog can also be shown to highlight that the app

    is processing some information or waiting for more data etc.o create a

  • 8/13/2019 Digit Devworx March 2013

    62/100

    60 GUI DEVELOPMENT

    simple dialog we must use the AlertDialog API

    AlertDialog.Builder builder = new AlertDialog.

    Builder(getActivity());

    builder.setMessage("This is what you must be aware

    of")

    .setTitle("My dialog");

    AlertDialog dialog = builder.create();

    then to show the dialog, you must use the show method

    on the dialog

    dialog.show();

    Remember you can also create complex dialogs with buttons and

    listeners for those buttons as well.

    dialog.setPositiveButton("Okay", new DialogInterface.

    OnClickListener() {

    @Override

    Suggested pattern for grid view Source: developer.android.com

  • 8/13/2019 Digit Devworx March 2013

    63/100

    61GUI DEVELOPMENT

    public void onClick(DialogInterface

    dialog, int id) {

    // do something when the user

    clicks okay

    }

    })

    .setNegativeButton("Cancel", new

    DialogInterface.OnClickListener() {

    @Override

    public void onClick(DialogInterface

    dialog, int id) {

    // do something when the user says

    cancel

    }

    });

    Inside the button's respective OnClickListener, we can specify the

    action that needs to be performed when the Okay or Cancel is pressed.

    NotificationsNotifications is one of the hallmark features of the Android platform.

    It is basically a message that is dis-

    played outside the user's normal

    user interface. Developers can first

    show a notification icon in the noti-

    fication tray at the top of an Android

    device, once the user opens the noti-fication drawer, he/she has access to

    the complete notification.

    Starting with Android 4.1, noti-

    fications are now expandable in

    nature and one can expand the ini-

    tial notification to show more data

    and even provide actionable buttonsbuilt right into the notification.

    A notification is typi-

    cally created by using the

    NotificationCompat API

    NoticationCompat.Builder

    Additional menu

  • 8/13/2019 Digit Devworx March 2013

    64/100

    62 GUI DEVELOPMENT

    builder =

    new NoticationCompat.Builder(this)

    .setSmallIcon(R.drawable.musicicon)

    .setContentTitle("Song playing")

    .setContentText("Its my life");

    PendingIntent pendingIntent = PendingIntent.

    getActivity(this, 0, new Intent(this, MyActivity.

    class), 0);

    builder.setContentIntent(pendingIntent);

    NoticationManager nticationManager =

    (NoticationManager) getSystemService(Context.

    NOTIFICATION _ SERVICE);

    noticationManager.notify(1234, builder.build());

    Here we create the notification using the NotificationCompat.Builder

    object and then give it an icon, title and text so that the notificationitself is well defined.

    Next we give the notification a PendingIntent, by giving a Pendin-

    gIntent to the notification, you are basically giving the notification the

    right to perform an action on the behalf of the application. In our case,

    Example of a detailed notification. Source: developer.android.com

  • 8/13/2019 Digit Devworx March 2013

    65/100

    63GUI DEVELOPMENT

    we are giving the notification the right to launch our activity MyActivity

    when we click on it.

    Ultimately we must use build on the NotificationCompat.Builder to

    create the notification and then use the NotificationManager object to

    actually display the notification.

    So now weve gotten a good understanding of all the basic View and

    ViewGroups in Android, with this knowledge we can build anythingfrom the very basic to the very complex of applications.

    Additional notification

    Notification on file information during playback

  • 8/13/2019 Digit Devworx March 2013

    66/100

    CHAPTER 5

    Android NDKMOST BASIC ANDROID apps run well on the Dalvik VM and are

    portable enough to run on any type of hardware even if the hardware

    architecture changes for example from ARM to x86. But in cases when

    heavy computations are to be done like computationally intensive games,

    which require physics simulation to be done, it would take NDK to solvethe problem and uncap the kind of performance that an app cannot be

    achieved under the Dalvik VM. It is however not recommended simply

    for the purposes of developer's preferences or because the developer

    only knows a specific language. Actually, before even attempting to use

    the NDK it is suggested that a developer be sufficiently comfortable at

    developing in Android and proficient at both Java and C languages.

  • 8/13/2019 Digit Devworx March 2013

    67/100

    65ANDROID NDK

    To have more clarity on what NDK really is, it should be emphasized

    that it allows mixing some parts of native code in C and C++ with an

    Android app developed in Java. It is based on JNI i.e. Java Native interface

    and provides headers and native libraries to interact with the user and letsyou perform computations at a much faster speed natively on the hardware.

    This however does not change the way in which the final application is

    packaged and the way in which the overall application is managed in its

    lifecycle. It is also wrong to assume that all type of applications will benefit

    if the code runs natively with the help of the NDK, in fact a major drawback

    for many will be that it will increase code complexity exponentially and

    the overhead incurred by the exchanges between Native code and otherparts of the application will also be significant enough that it cannot be

    overlooked during its execution.

    Android first started supporting NDK since Android 1.5 Cupcake

    and features like Native Activities and x86 support started coming into

    picture only since Android 2.3 Gingerbread. Due to this, there have been

    two ways to write an Android app since Android 2.3, one is to use JNI,

    which offers you flexibility and availability of the Android framework,while writing code using Native Activities offers the opportunity to handle

    application lifecycle callbacks from the native code itself. The result is that

    these lifecycle events like onPause(), onCreate() are handled within the

    native code itself but with less featues like services and content providers

    not being available, which need to be accessed through JNI only. The

    most recent release of Android NDK supports the following instruction

    set architectures: ARMv5TE, including Thumb-1 instructions

    ARMv7-A, including Thumb-2 and VFPv3-D16 instructions, with

    optional support for NEON/VFPv3-D32 instructions

    x86 instructions

    MIPS instructions

    With the help of NDK, you can take advantage of the SIMD extensions

    to speed up the execution of your application. These are mainly used forMultimedia applications and can provide performance gains of several

    orders of magnitude greater than before. The ARM instruction set exten-

    sion that supports this is known as NEON, while Intel CPUs support SSE3

    (Supplemental Streaming SIMD Extensions) and older versions like SSE2,

    SSE and MMX. There are a couple of API incompatibilities that may occur

    when targeting applications that utilize both of these.

  • 8/13/2019 Digit Devworx March 2013

    68/100

    66 ANDROID NDK

    The Android NDK also includes a set of cross compilers and native API

    libraries which provide headers to be used in development of the native

    application. The Android official documentation lists out the libraries

    which are stable and safe to use, while most others are experimental andare likely to change in future versions of Android NDK. These stable

    libraries are: -

    libc (C library) headers

    libm (math library) headers

    JNI interface headers

    libz (Zlib compression) headers

    liblog (Android logging) header OpenGL ES 1.1 and OpenGL ES 2.0 (3D graphics libraries) headers

    libjnigraphics (Pixel buffer access) header (for Android 2.2 and above).

    A Minimal set of headers for C++ support

    OpenSL ES native audio libraries

    Android native