Android Platform and Applicatio_Android

Document Sample
 Android Platform and Applicatio_Android Powered By Docstoc
					Politecnico di Torino - III Facoltà di Ingegneria
      Corso di laurea in Ingegneria Informatica

            Android Platform
         Application Development

                 Tutore Accademico
                Prof. Marco Torchiano

                   Luca Belluccini

Introduction, 3
Objectives, 3
          1.1.Features, 5
                    1.1.1.Application framework, 5
                    1.1.2.Dalvik virtual machine, 5
                    1.1.3.Integrated browser based on the open source WebKit engine, 5
                    1.1.4.Optimized graphics based on SGL libraries, 5
           graphics based on the OpenGL ES 1.0 specification, 5
                    1.1.6.SQLite, 6
                    1.1.7.Media support, 6
                    1.1.8.GSM Telephony, EDGE, 3G (hardware dependent), 6
                    1.1.9.Bluetooth and WiFi (hardware dependent), 6
                    1.1.10.Camera, GPS, compass, and accelerometer (hardware dependent), 6
                    1.1.11.Android SDK and Eclipse IDE plugin, 7
          1.2.Architecture, 9
                    1.2.1.Linux Kernel, 9
                    1.2.2.Libraries, 9
                    1.2.3.Android Runtime, 10
                    1.2.4.Dalvik virtual machine, 10
                    1.2.5.Application Framework , 11
                      View System, 11
                      Manager, 11
                      Providers, 14
                      Manager, 15
                      Manager, 16
                      Manager, 17
                    1.2.6.Applications, 17
                     , 17
                     , 18
                     , 19
                      and permissions, 19
          2.1.Introduction, 21
          2.2.Application overview, 21
          2.3.Implementation, 22
                    2.3.1.Login Activity and User Activities, 22
                      Activity, 22
                      Database Adapter, 24
                      Activity, 25
                      and User Activity layouts , 26
                    2.3.2.Accounts and Account Activities, 27
                      Activity, 27
                      Database Adapter, 29
                      Class, 29
                      API porting, 30
                      Activity, 31
                    2.3.3.Mails activity, 32
                     , 33
                      Adapter, 34
                    2.3.4.Mail activity, 34
                      class and LocalMessageElement interface, 34
                     , 35
                      and DummyTrustManager classes, 35
          2.4.Improvements, 36
          2.5.Android lacks, 36
          2.6.Testing and debugging, 37
          2.7.APK package creation, 38
          2.8.Learning curve and Android framework learning time, 39
License, 40
Bibliographic citation, 40

        Open Handset Alliance, a group of more than 30 technology and mobile companies have
developed Android, a complete and free mobile platform.
The first version was released on November 2007.
A distinctive feature of this software solution is that it is also open.
Google, one of the key partners of the alliance, started the Android Developer Challenge, which put
at stake ten million dollars to developers who build apps on this platform.
        Soon, developers got SDK (Software Development Kit) and started writing applications.
A new programming community, focused on Android, is growing: it is made up of forums, blogs
and newsletters.
During the second half of 2008 will be released mobile phones and smartphones based on this
operating system.

       The aim of this report is to explain what is Android and illustrate the steps necessary to
develop a small application.
The application is a mail client and contains some little examples showing features of this mobile
phone software stack.
The report will also focus on programming issues.


       Android is a software for mobile devices, which consists of an operating system,
middleware and main applications.
The full project is released under Apache version 2 license: there is no copyleft clause so mobile
operators, software companies and virtually everyone can add or remove features.
Therefore, there is no difference between core applications and third-party ones. Core applications
could be fully re-written.
The platform is built over a Linux Kernel, wrapped up by a custom virtual machine (Dalvik VM),
designed to optimize memory and hardware resources.
       As Web 2.0, information sharing between different processes and applications is possible
and made simple by a sort of interface called "Content Provider".
There are few native content providers ( e.g. media, contacts, etc. ) and new ones can be added,
enabling the developer to build rich peer-to-peer applications.

1.1. Features
1.1.1.Application framework
        The application framework is provided to standardize software structure and to make code
Android, by using classes and interfaces, defines the basic flow. The programmer must only inject
the code necessary to implement application algorithm.
In certain cases, frameworks are subclassed or extended, with the aim of add new functionalities.

1.1.2.Dalvik virtual machine
        This register-based virtual machine was designed and written by Dan Bornstein with
contributions from other Google engineers.
On Android operating system, multiple Dalvik VM instances are running at the same time. Each
service or application runs into its own virtual machine and each one on a different process.
In limited resources environment such as mobile phone, efficient memory management and a light-
weight threading support is very important to make applications and multitasking fast and reactive.
        Moreover, allocating a single process for each virtual machine, prevents all the other
applications from being closed if one of them crashes.

1.1.3.Integrated browser based on the open source WebKit engine
        The increasingly number of smartphones equipped with Wi-Fi antennas made essential the
presence of a reliable web browser.
WebKit is open source software with portions licensed under the LGPL and BSD licenses. These
kind of licenses make WebKit freely usable for both open source and proprietary applications.
This web content engine allowed programmers within the alliance to develop a standard-compliant
web browser without reinventing the wheel.
One important goal of the WebKit is maintaining and improving speed and memory use.

1.1.4.Optimized graphics based on SGL libraries
       The graphics subsystem is based on SGL (Scalable Graphics Library). It is the library on
which the higher-level layers (WindowManager and SurfaceManager) of the framework are
The original user interface is two-dimensional and SGL were optimized to be suitable for embedded
devices. graphics based on the OpenGL ES 1.0 specification
       Android includes support for 3D hardware acceleration. This functionality is accessed via
the OpenGL API — specifically, the OpenGL ES API. OpenGL ES is a branch of the OpenGL and
were designed for embedded devices.
The OpenGL ES is quite different from basic OpenGL programming method. Android currently
supports OpenGL ES 1.0, which corresponds to OpenGL 1.3.
The specific API provided by Android is similar, but not identical, to the J2ME JSR239 OpenGL

        SQLite is a software library that implements a SQL engine. It has been used with great
success as on-disk file format: allows the developer to handle data in a simple way, but also have
the use of database features (such as undo, redo, etc.).
In embedded device environment, in which there is low-concurrency and there are little or medium
size datasets, SQLite is the right choice.

1.1.7.Media support
        Mobile phones, in the last years, became a personal media centre: users store on them songs,
photos and videos.
Although there is no built-in media player, Android is ready to support for common audio, video,
and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF).

1.1.8.GSM Telephony, EDGE, 3G (hardware dependent)
         Android, if installed on GSM-capable hardware, allows developers and users to
communicate via the most popular standard for mobile phones in the world.
So, it is possible to make voice calls and send text by using Short Message Service over the GSM
GSM improved in the last decade, adding packet data capabilities (GPRS) and higher speed data
transmissions (EDGE). Both features are hardware dependent.
The last evolution of mobile communication is represented by third-generation (3G) cell phone
technologies. It offers support for the last internet protocol (IPv6), multimedia messaging,
videoconferencing and mobile tv.

1.1.9.Bluetooth and WiFi (hardware dependent)
        Bluetooth is a wireless protocol, optimized for short-range transfers. Android offers support
for Bluetooth devices, enabling different ways of operate: acting as a serial line or as a PAN
(Personal Area Network).
        This technology permits users to transfer data or communicate without relying on a network
and last but not the least in a mobile device, having less power consumption.
On the other hand, WiFi is useful when necessiting of higher throughput and communications
involve greater distances. A device which can access the internet via WiFi could be useful,
especially when WiFi spots are spreading.

1.1.10.Camera, GPS, compass, and accelerometer (hardware dependent)
         Android has some built-in layers between operating system and GPS. That provides the
developer (and the user) to provide a navigation system or a new kind of applications (which rely
on the real-time global position).
This platform also offers interfaces to a compass or an accelerometer. The second one is very useful
for improving user interface: it is possible to detect the device orientation and rotate the content, to
keep it readable.
It is also provided a simple way to access data retrieved from an optional digital camera.

1.1.11.Android SDK and Eclipse IDE plugin
        The SDK contains a set of tools to build applications for the Android platform. Until now,
there have been 5 updates.
Android SDK is made up by:
    • Emulator
    • Tools and utilities
    • Eclipse Plugin
    • Documentation (and a offline copy of Android website)

The whole SDK is supported on the following operating systems:
   • Microsoft platform (XP or Vista)
   • Mac OS X 10.4.8 or later (x86 machines only)
   • Linux

To develop Android applications, it is possible to use one of the following Development
   • Eclipse IDE, based on
         o Europa version, from 3.2
         o JDT plugin
         o WST plugin (optional)
         o JDK 5 or 6
         o ADT, the Android Development Tools Plugin (optional but recommended)
   • Other IDEs such as
         o JDK 5 or 6
         o Apache Ant 1.6.5 or later for Linux and Mac, 1.7 or later for Windows

In both cases, Android SDK is not compatible with Gnu Compiler for Java (GCJ).
Before installing SDK, I was expecting much more automatic-code generation (e.g. wizards for
creating menus, interfaces, etc.): then I realized that ADT only helps the developer in some
The Eclipse ADT plugin:
    • Generates pointers to the application resources in the R class. Resources are animations,
        drawables, raw data, xml, values, etc.
    • Provides a minimal interface to application properties, letting the developer to define
        permissions, activities and other features of the package. AndroidManifest.xml
        describes global values for your package, including the application components (activities,
        services, etc.) that the package exposes and the implementation classes for each component,
        what kind of data each can handle, and where they can be launched.
    • Contains a Project Fixing tool, for removing bugs from imported projects
    • Contains a tool which generates the package for distributing your application. The generated
        APK file is a compressed collection of an AndroidManifest.xml file, application code
        (DEX files), resource files, and other files.
    • Provides a graphical interface for defining options when launching device emulator (kind of
        device, network speed, mounted storage drives)
    • Builds and installs projects into the current emulated device (if any) in DEX files (Dalvik’s

The SDK ships with a useful GUI debugging tool, the DDMS (Dalvik Debug Monitor Service). It
provides screen capture, log dump, and process examination capabilities.

1.2. Architecture
       Android is based on different components. The image below gives a more detailed
description of how hardware is abstracted and the structure of application framework.

1.2.1.Linux Kernel
        At the bottom of the hierarchy there is the Linux Kernel. Basically, it is the 2.6.4 version of
Linux Kernel, to which are applied Android specific patches.
This element is responsible of managing the core system services and driver model.
        Accessing the device in shell mode (command line mode), it is possible to know how
filesystem is structured and which kind of filesystem is used.
The root filesystem is using rootfs, whereas data and system are using YAFFS.
YAFFS is a filesystem designed specifically for NAND and NOR Flash drives.

Application framework and Android runtime rely on a set of C/C++ libraries.
   • System C library - a BSD-derived implementation of the standard C system library (libc),
       tuned for embedded Linux-based devices
   • Media Libraries - based on PacketVideo's OpenCORE; the libraries support playback and
       recording of many popular audio and video formats, as well as static image files, including
       MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG
   • Surface Manager - manages access to the display subsystem and seamlessly composites 2D
       and 3D graphic layers from multiple applications
   • LibWebCore - a modern web browser engine which powers both the Android browser and
       an embeddable web view
   • SGL - the underlying 2D graphics engine
   • 3D libraries - an implementation based on OpenGL ES 1.0 APIs; the libraries use either

       hardware 3D acceleration (where available) or the included, highly optimized 3D software
   •   FreeType - bitmap and vector font rendering
   •   SQLite - a powerful and lightweight relational database engine available to all applications

1.2.3.Android Runtime
        Android runtime consists of Core libraries and the Dalvik Virtual Machine. Core libraries
offer most of Java standard libraries.
        Dalvik is optimized to allow multiple instances of the virtual machine to run at the same
time in limited memory, and each Dalvik application runs as a separate Linux process.

1.2.4.Dalvik virtual machine
        As mentioned in the first part of this document, Android is not using Java bytecode, but a
custom one.
The first differences which is noted between Dalvik and a standard Java virtual machine (JVM) is
that Dalvik is register-based, whereas JVMs are stack-based. Register-based virtual machines
allows greater ahead-of-time optimization, which is beneficial in constrained environments like
mobile phones.
        The standard Java Virtual Machine has 2 main issues: interpreter complexity and bigger
quantity of memory required for paging. The chosen solution for Android is similar to Java Card
technology ( ) which is used in very limited resources devices (Smart
cards or RFIDs).
        When building an application, a tool called dx turns the Java Class files of Java classes
compiled by a regular Java compiler into DEX file format (Dalvik Executable). Once these files are
packed into a single APK package and transferred to the device, the Dalvik bytecode is checked and
are performed additional optimizations.

         The Dalvik VM, at present, cannot generate Java code on the fly. This means that it is not
supporting dynamic languages or Just-in-time compilation (JIT).
Just-in-time compilation is used to improve virtual machines performances: using this technology,
at the time the bytecode is interpreted, the JIT compiler will compile the upcoming code (whole file,
a function or an arbitrary code fragment).
Finally, the constant pool table used in Classes, where most of the literal constant values are stored,
has been modified to use only 4 byte long indexes, to simplify the interpreter.
         The Dalvik VM and its bytecode executes Java code using less power (fewer CPU and
memory cycles) and in less space.
Register-based virtual machines requires fewer executed instructions, but using larger code size. In
any case, the increased cost of fetching bigger code involves a short time.
         Dalvik uses Apache Harmony (which is under Apache License) instead of OpenJDK (which
is under a modified GPL), allowing device makers to modify the core JVM without having to

distribute their source code.

1.2.5.Application Framework
       Application framework is a huge set of classes, interfaces and packages. They allow a easy
way to manage graphical user interface, access resources and content, receive notifications or
handle an incoming call. Let’s focus on some elements. View System

        User interface are implemented by using android.view.View. This class is the basic
UI building block. There are different extended classes, providing the most suitable interface for
every kind of application. View class serves as a base class for widgets. Widgets are screen
elements: there are controls (such as buttons, checkboxes, etc.) and elements capable of displaying
text, images (text fields, select elements, etc.) or rendering web pages.
        The android.view.ViewGroup is another class whose function is to contain and
manage a subordinate set of views and other viewgroups. By using ViewGroups, the developer can

build up a tree of views, which becomes the graphical user interface layout.
User interface layout can be defined programmatically or using XML files. The XML layout files
should be stored in the res/layout folder, making easier the retrieval in every operation
referencing to it. There is a schema defining rules of XML layout file, which help the developer to
write valid user interfaces.
        The widgets contained in each view and the views themselves can be accessed by using their
id. The id must be defined as property of the screen element in the layout definition and must be
        The Activity attach the layout calling setContentView() method, passing it the
reference to the root node of the tree. When the Activity becomes active, the system requests the
root node to start recursive call of measuring and drawing methods, down to the children elements
of the tree.
Each View renders itself but layout parameters (such as width, height) must be appropriate for its
        There are different kind of listeners, which react on different actions, such as key press, a
screen touch for touch capable devices. Manager

       The is the class which is used to implement a part or a whole

application. It is a specific task provided to an user. For example, if your application is a notepad,
there will be two different Activities: one for displaying a list of notes which were written and
stored on the device and another one for editing or writing new ones.
        Each activity has its layout and permission. Being an extended class of
android.content.Context, it inherits methods and fields whose allow access to application-
specific resources and classes, as well as up-calls for application-level operations such as launching
sub activities, broadcasting and receiving intents.
        To be of use with Context.startActivity(), all activity classes must have a
corresponding <activity> declaration in their package's AndroidManifest.xml.
        The activities are handled as a stack. When a new activity is launched, it is placed on the top
of the stack, becoming the running activity. The previous activity is placed in background and it
will not came out from this state until the activities over it exit. The activity has a lifecycle and can
be defined 3 different states:
    • Running
        When the activity is started, it performs:
            o onCreate() method, in which activity receives a Bundle object. Bundle object
                 is a sort of box in which can be stored and retrieved primitive data types
            o onStart() method, when activity is becoming visible to the user. Always
                 followed by
            o onResume() method, and now activity is at the top of the activity stack
        The activity is now in running state.
    • Paused
        For example, if the “Home button” is pressed when running an activity, are called:
            o onFreeze() method, allows the developer to save away your current state; it is
                 always followed by
            o onPause() method, when the system is about to start resuming a previous activity
                 (in this case, as default, is displayed the main screen of Android OS). This method is
                 usually overloaded for committing unsaved changes to persistent data, stop
                 animations and other things that may be consuming CPU, etc. Implementations of
                 this method must be fast, because the next activity will not be resumed until this
                 method returns.
        Followed by either onResume() if the activity returns back to the front, or onStop() if
        it becomes invisible to the user.
        In this state the activity could be killed or asked for finishing if there are other applications
        starving of memory.
    • Stopped
        In this state, onStop() method is called. The activity is no longer visible to the user.
        Followed by either onRestart() if this activity is coming back to interact with the user,
        or onDestroy() if this activity is going away.
The onDestroy() method is the last call before activity is destroyed. That could happen in two
cases: another application needs memory or the activity is exiting properly by using finish()
method. It is possible to distinguish between the cases checking isFinishing() method.
        Lifecycle is represented by the following flowchart.

        Activity behaviour and configuration can be set and changed by using
android.content.Resources.Configuration class. Preferences can be also stored and
retrieved within the application package by using Context.getSharedPreferences()
method. The getPreferences() method allows the developer to retrieve and modify a set of
name/value pairs associated within a single activity.
        Before starting a sub activity, it is necessary to create a Intent object.
The android.content.Intent class provides a facility for performing late runtime binding
between the code in different applications.
The Intent brings two important information: the action identifier corresponding to the task will
be performed and the data to operate on, expressed as a Uri (Uri are described in Content Provider
section of this document). That solution offers a robust structure for Application and Activity
If the applications are well designed, it is possible to filter intents (by using Intent parameters
such as action, data, type, category and so on) and route them to a specific activity which

will perform the necessary operations.
        The Intent routing (or resolution), can be explicit or implicit. Explicit resolution means that
in the method call is specified the exact class to be run. For using Implicit resolution, the developer
must include enough information to enable IntentFilter to choose the right Activity or
Service to be run.
        Activities and Views are tightly linked. There are activities using in their layout
AdapterView elements, written for specific tasks such as:
    • ExpandableListActivity, ListActivity, providing an efficient interface in case
        of there is a list of elements to be displayed, expanded and selected
    • MapActivity, which is useful when is necessary a MapView. The MapView is a view
        which displays a map
To make it more clear: ListActivity displays a list of items by binding to a data source such as
an array or Cursor, and exposes event handlers when the user selects an item. The screen layout is
a single, full screen list. If the list is empty, can be specified a custom view, for example a
TextView displaying “No entry” message.

The developer must specify the layout of individual rows in the list. There are few default layouts,
but new ones can be added. The AdapterView.OnItemClickListener member let the
programmer to handle user selections.
         The developer is helped by Adapters on Data Binding. An object implementing Adapter
interface acts as bridge between an AdapterView and the underlying data for that view. The
Adapter provides access to the data items.
It is possible to define custom adapters or extend the default ones. The adapters shipped with the
framework are mostly based on arrays or database cursors.
         The Service abstract class is a special kind of Activity. It is designed for applications
performing tasks in the background, not interacting with the user, for an indefinite period of time.
Each Service class must have a corresponding <service> declaration in its package's
Services can be started with Context.startService() and Context.bindService().
It is necessary to distinguish their behaviour:
     • startService() method should be used if it is necessary to launch a long-running
         background task, whose lifecycle is not related to the lifecycle of the Activity that started it.
         There is no communication between caller and service, unless the Bundle object
     • bindService() method should be used if caller and service lifecycles are tied. The
         Activity using the service is notified about the state of the service. It is also possible to
         communicate via Android IDL (AIDL) framework Providers
        To share data, such as contacts, images, files, it is possible to create or use a
This is the only way to share data across packages; there is no common storage area that all
packages can share, except memory card drive.
To create a ContentProvider, the first step is to extend the ContentProvider class. After
that, the primary methods that need to be implemented are:
    • query, which returns data to the caller
    • insert, which inserts new data into the content provider
    • update, which updates existing data in the content provider
    • delete, which deletes data from the content provider
    • getType, which returns the MIME type of data in the content provider

All methods are based on the abstract class. This class allows you to create,
decode, parse, and examine URI reference objects that conform to RFC 2396. Lets examine an

   A. Is a standard prefix. It is never modified.
   B. It is the authority part. It must be unique and defined in the element's authorities attribute:
      <provider class="ShopProvider" authorities="”
   C. Data type token. This is a virtual path: it could match with a database table name or a folder
      of the filesystem. The programmer is free to choose a possible implementation.
   D. It is the _id value of a specific requested record.

In the example Uri, we are requesting the product, provided by, having id
value of 123.
        How a content provider actually stores its data under the covers is up to the implementation
of the content provider, but all content providers must implement a common convention to query
for data, and a common convention to return results.
After a short analysis, it is clearly visible that ContentProvider is database centric. Most of the
methods must return an object implementing android.database.Cursor. This interface
provides random read-write access to the result set returned by a database query. Manager

        Static non-code data, such as images, strings, constants or raw files can be arranged in a
specific project subdirectory. This kind of data is called resource.
        The Android resource compiler, called aapt, compiles the resources into the application
binary, according to which subfolder they are in. Developer can use the Resources class to
access the application's resources; the Resources instance associated with your application can
generally be found through Context.getResources().
        There are different types of supported resources. Here is a list of each resource type, its file

format and a short description.

Directory    Resource type
res/anim/    Animation resource: it can be defined by using an XML file, which contains
             code for describing a frame-by-frame or tweened animation.
res/drawable A renderable resource: it can be a bitmap file (a PNG, JPG or GIF file), a color
             (which is defined by its hexadecimal value) or a Nine-Patch (a stretchable
             image, mostly used in skinned controls, such as an image button).
res/layout   A layout resource: it is an XML file containing a whole screen or a part of a
             screen layout definition. Each XML file must evaluate to a single root element.
             Each      root     element      must     have      the     Android    namespace
    defined in it.
res/values   A resource containing one or more values. They must be defined within one or
             more XML files.
             There are 5 types of value resources:
                 • arrays.xml to define arrays
                 • colors.xml to define color drawables and color string values. They
                     can be retrieved by using Resources.getDrawable() and
                 • dimens.xml to define dimension value. This kind of re source is
                     widely used in layout resources. Can be retrieved using
                 • strings.xml to define string values.
                     To get these resource, use Resources.getString() or preferably
                     Resources.getText(). The second method will retain any rich
                     text styling which is usually desirable for UI strings.
                 • styles.xml to define style objects.
res/xml      Arbitrary XML files that are compiled and can be read at run time by calling
res/raw      Arbitrary files. They are added uncompiled to the compressed file that
             application build produces. To use these resources,                there is the
             Resources.openRawResource() method

        Android documentation also presents a method to use “alternate resources”.
If the developer wants to differentiate content, layout or language according to device specifications
or user preferences, this is attainable by storing resource files in res folder by using qualifiers.
Android supports several types of qualifiers, with various values for each.
        There is no official support for internationalization, but documentation contains a notice
saying it could be implemented in further versions of Android. Manager

       There is a class to notify the user of events that happen. Notifications can take different
   • A persistent icon that goes in the status bar and is accessible through the launcher, (when the

       user selects it, a designated Intent can be launched)
   •   Turning on LEDs on the device, alerting the user by flashing the backlight, playing a sound,
       or vibrating.

     Notifications can be used             by    retrieving   the   pre-instantiated   object,   through
getSystemService() method. Manager

        Applications access to device telephony capabilities by using Telephony Manager.
Activities using android.telephony package must include CALL_PHONE permission in their
AndroidManifest.xml file.
Android provides telephony functionality to programmers through:
   • A native Intent receiver sending a CALL_ACTION intent providing a phone number Uri
   • The IPhone interface to dial a number, end a call, check radio on/off state, or turn the radio
        on or off
   • The DataStateIntentReceiver or PhoneStateIntentReceiver to register for
        events, or to query phone or data connection information such as:
            o Call state and call state change (IDLE, RINGING, OFF_HOOK)
            o Service states and state change (in service, out of service, emergency only, powered
                off, roaming, operator name, and so on)
            o Signal strength
            o Voicemail alerts
            o Data connection and activity state (disconnected, connecting, connected, data in or
   • The TelephonyProperties, which allows to retrieve properties, such as SIM serial
        number, phone and voice mail numbers, IMEI number, and so on
   • SmsManager, which allows to send and receive SMS data, text, and raw PDU messages


A developer writing an application using a new framework:
    • Learns how to use the APIs to do the necessary tasks
    • Learns how tasks should be built. That second phase can often take a long time.
The best applications usually provide an outstanding user experience.
       There are three key characteristics in a successful software: it is fast; it is responsive; and it
is seamless.

       Instead of fast, efficient word should be used.
For embedded applications like cell phones, Moore's Law is usually exploited to make phones
smaller and make batteries last longer.
As a result, embedded devices like phones are increasing in actual, raw speed much more slowly
than desktop systems.

        In object-oriented terms, most of this work takes place at the method level, on the order of
actual lines of code, loops, and so on.
Android devices are embedded devices. There are two basic rules for resource-constrained systems:
    • Don't do work that you don't need to do.
    • Don't allocate memory if you can avoid it.
Let’s focus on classes.
        Object creation is a heavy operation: the advice is to avoid creating short-term temporary
objects if possible. Fewer objects created mean less-frequent garbage collection, which has a direct
impact on user experience.
        Another tip is about objects declaration. For example, an HashMap can be defined in two
different ways:

Map myMap1 = new HashMap();
HashMap myMap2 = new HashMap();

Conventional wisdom says that the first one should be better, because it allows you to change the
underlying implementation to anything that implements the Map interface. But in embedded system
the developer should consider that calling through an interface reference can be two times longer
than a method called through a concrete reference.
         Descending to class elements, developers are recommended to avoid internal getters and
setters, accessing to class fields directly.
Costants should be declared with the final keyword: constants are placed in classfile static field
initializers, which are directly handled by the VM.
There is no immediate performance improvement, but if the compiler knows that a getter method
can't be overridden by a sub-class, it can inline the method call.
         Avoid Float data type, if possible, cause of embedded CPU limitations: usually it has no
hardware floating point support, so operations are performed in software.
         Talking about flow control structures, the developer should keep in mind that enhanced for
loop syntax must be used with caution: in this kind of instructions, there is implicitly object

Applications must be responsive. Activities making the system busy will generate a "Application
Not Responding" (ANR) message.
        If the application spends too much time building an elaborate in-memory structure, or doing
complex calculations, the system will conclude that your application has hung.
        Android will display the ANR when it one of the following conditions happen:
    • no response to an input event (e.g. key press, screen touch) within 5 seconds
    • an IntentReceiver hasn't finished executing within 10 seconds
Generally, 100 to 200ms is the threshold beyond which users will perceive a sort of delay in an
If there is a lot of work to do, the developer should put the “heavy” block of code in a thread and
show the user its progress (a ProgressBar or a ProgressDialog are useful for this purpose).

        If the application has a time-consuming initial setup phase, the programmer should consider
to place a splash screen on the screen or to render the main view as soon as possible, even if the
start-up is not completed.
Responsiveness is a class level problem.

         In mobile devices, asynchronous events are common. The application must be robust in case
of another Activity is coming to foreground for user input or for displaying information. To the
other side, the application cannot annoy users, popping up a UI every time it needs user interaction.
Instead of spawning Activities directly from the background, the developer should instead use the
NotificationManager to set Notifications.
         Android's application model is constructed to let a smooth and simple switch between
activities or applications.
The Android system is designed to treat applications as a sort of federation of loosely-coupled
components, often sharing data in some way.
         The "Android Way" to share data is to create a ContentProvider to expose them to
other applications via a clean, well-thought-out, and maintainable API.
         Another thing to keep in mind is that Android applications that accept or edit input should
override the onFreeze() method and save their state: it is very important to do not loose data.
         The programmer must partition the application, being sure to make effective use of
         Users are expecting simple but good-looking and operational graphical user interface. One
tip for developers is to extend themes and make use of relative layouts. If this work is well done, the
system will handle the rest, and application will look great on any device.
         If an application uses network, the programmer should assume the network is slow and
should minimize network accesses and bandwidth.
         Battery life is very important: developer priority is to minimize the power drain from using
the radio or CPU intensive calculations, also being sure to handle error conditions gracefully. and permissions

Android OS runs in a multi-process system, where each application runs in its own process.
Low level permissions are provided by the standard Linux facilities, such as user and group IDs,
that are assigned to applications.
        Each Android package file installed on the device is given its own unique Linux user ID,
creating a sandbox for it and preventing it from touching other applications (or other applications
from touching it).
        If the developer wants to share data such as files or databases between two applications, they
must be signed with the same signature and requesting the same sharedUserId.
        Any files created by an application will be assigned that application's user ID, and not
normally accessible to other packages. There are also methods whose allow to make generated files
“world readable”.
        To make use of protected features of the device, you must include in your
AndroidManifest.xml one or more <uses-permission> tags declaring the permissions that
your application needs.

At application install time, permissions requested by the application are granted to it by the package
installer, based on checks with trusted authorities and interaction with the user. No checks will be
done at runtime. If an Activity being part of the application wants to make use of a feature which it
is not permitted to use, will be thrown a SecurityException.
        The standard permissions provided by the Android system can be found at
Manifest.permission. Any application may also define and enforce its own permissions.
Permissions can be enforced for:
    • Activities
    • Services
    • IntentReceivers
    • ContentProviders
    • Broadcasting Intents


2.1. Introduction
         This document contains an analysis of application development on Android platform.
The application is a small mail client, capable of retrieving emails both using POP3 and IMAP
protocols. Both protocols can be used under SSL Security enhancement.
         It supports multiple user accounts and mail accounts. Even if a mobile phone is usually a
personal device, this feature could be useful within a company.
In fact, these phones are shared by different employees and each one has different email accounts to
keep track of.

2.2. Application overview
        The application is called “Mail Android” and is made up by the following modules:
   • A login screen, which contains controls to log in. This module gives access to an
        interface, called
            o user, for creating, editing or deleting user accounts
   • A mail accounts list, accessible only if the user is logged in. This Activity gives access to
        an interface, called
            o account, letting the user to create, edit or delete mail accounts.
   • A module called mails that, after user confirmation, retrieves the whole email folder.
   • A module called mail, showing an email selected from the mails Activity
The listed modules are implemented by using an Activity for each one.
These Activities are “nested”: the user gets access to a module only if a user input or/and a
permission were given by the previous ones.

       Affirm that Activities are nested is similar to say that they’re organized as an Activity stack.
So the Android Activity structure fits perfectly our requirements.

Mail android needs classes, interfaces or whole libraries for:
   • Displaying a graphical user interface
   • Splitting the application in independent modules
   • Storing data
   • Connecting to and retrieving emails from network
   • Rendering emails written in HTML language or containing attachments
       Graphical UI is provided by the Android View system. There are no custom views to
implement. Strings used within the application are placed in strings.xml resource file.
Mainly, there will be used:
   • LinearLayout elements as containers for other types of views that must be placed in
       horizontal or vertical order.
       Mostly, layouts are built using one or more of the following views:
           o TextView, used for displaying text or labels
           o EditView, for user input fields
           o Spinner, used to let user select an item from a list of choices
           o ListView, which is used to show items in a vertically scrolling list
           o ScrollView, which is used as a scrollable container, for content exceeding screen
           o WebView, capable of rendering HTML code, plain text or images
       Data storage is provided by the internal SQLite database.
       Network access and message communication (Mail Android can only download emails) is
based on Sun JavaMail API.
       Email content can be rendered by using the built-in browser: it can be embedded in any
       As specified in the overview, Mail Android is divided into six activities: two of them are
used for editing a user account or an email account. The other 4 activities are more complex.

2.3.1.Login Activity and User Activities Activity

       LoginUI class extends Activity class.

        Firstly, the plan was to create a User class, containing all the data retrieved from the
database. Then, this choice was dismissed, due to memory usage and data redundancy.
This Activity is based on userDB object, which acts as an interface between the UI and the SQLite
        The onCreate method constructs the userDB object and resets the user interface. The
onCreateOptionsMenu method is overridden: the menu entries are defined there. The menu is
made of a list of entries. Each entry has its own ID, text label and an optional drawable object (such
as a PNG icon).
        The onMenuItemSelected method will be called every time a menu item is selected:
the item parameter permits to track which entry was selected. An internal switch control structure
calls the right function.
        loginUser is a simple method, that checks if username and password entered in
TextViews are matching an existing user, granting access to Accounts activity. If user exists,
its fetched id is passed to the Accounts activity through Intent object, which will use it to
retrieve the relative email accounts.

        createUser and editUser are similar methods: both will start the User Activity.
In the first case is passed a “dummy” user id, that will act as “new user” flag; in the second case,
username and password fields are checked, the matching id is fetched (if exists) and it is passed to
the User Activity. This activity will use the id to fetch the user data and fill the UI. The
image below is a screenshot of LoginUI Activity.

        Before focusing on User Activity, it is necessary to check UserDBAdapter class
structure. Database Adapter

       UserDBAdapter is a class offering a series of services: a method for creating the
application main database (if not present) and the user table (if the software is running for the first
time or table was not created) and wrapper methods for inserting, updating and deleting users
(which return error values in case of incompatible or wrong parameters).
The users table contains the following data.

Field label      Field type     Field properties                     Description
_id              integer        primary key autoincrement            Table Primary Key
_cid             integer        not null                             Contact ID Key, act as external key
                                                                     and it references to a contact id
username         text           not null                             User username
password         text           not null                             User password

       Field and methods of this class are listed below.

public class UserDBAdapter {
// Fields
// Omitted database constants
private SQLiteDatabase mDb;
private final Context mCtx;
// Methods
public UserDBAdapter(Context ctx) { ... }
public UserDBAdapter open() throws SQLException { ... }
public void close() { ... }
public long createUser(long cid, String username, String password) { ... }
public boolean deleteUser(Long rowId) { ... }
public Cursor fetchAllUsers() { ... }
public Cursor fetchUser(Long id) { ... }
public long fetchUser(String username, String password) { ... }
public long loginUser(String username, String password) { ... }
public boolean checkUser(String username) { ... }
public boolean updateUser(Long rowId, long cid, String username, String password) { ... }
        UserDBAdapter class retrieves and stores data into the SQLite database. Connection to
the database can be opened and closed, by using respectively open and close methods.
        The open method is also responsible of the database and table creation, if they are not
present. In any case, if an error occurs, a SQLException is thrown.
        createUser method is a wrapper for the INSERT query to the database: it calls
checkUser for checking if there is another user with the same username.
        A user can be fetched by using fetchUser methods (via id or username and
The fetchUser method implementation is listed below.

public Cursor fetchUser(Long id) {
        Cursor result = mDb.query(DATABASE_TABLE, new String[] {
          KEY_ID + "=" + id, null, null, null, null);
        if ((result.count() == 0) || !result.first()) {
                 return null;

       return result;
        Cursor object, returned from this method, will be used both from Login and User activities
to get the necessary data. In this case, the third parameter of query method represents the WHERE
clause of the SQL SELECT. All table field names are declared as class constants. Activity

       The UserUI Activity allows the user to create a user account or edit its information.

        User contact is a Spinner, filled with all contacts stored in the device. That is done in few
lines of code, requesting values to the ContentProvider.

Spinner contactS = (Spinner) findViewById(;

// projection: columns must be retrieved by ContentProvider
String[] projection = new String[] {
        android.provider.Contacts.PeopleColumns.NAME };

// managedQuery gets the Cursor object from ContentProviderURI
Cursor contactCursor = managedQuery( android.provider.Contacts.Phones.CONTENT_URI,
        android.provider.Contacts.PeopleColumns.NAME + " ASC" );

// contactAA is an object binding data from a generic array to the Spinner widget
ArrayAdapter<CharSequence> contactAA = new ArrayAdapter<CharSequence>(this,
CharSequence tempCS = null;
int selposition = 0;

if(contactCursor != null)
                       // code necessary to put Cursor entries into the ArrayAdapter
                       tempCS = contactCursor.getLong(
                               + " - " +

                       // condition for selecting a contact on user editing mode
                       lumns._ID)) == cid )
                               selposition = contactAA.getPosition(tempCS);

       The UserUI class structure is defined below.

public class UserUI extends Activity{
// Fields
// Omitted menu ID constants
private long userID;
private UserDBAdapter userDB;
// Methods
protected void onCreate(Bundle icicle) { ... }
public boolean onCreateOptionsMenu(Menu menu) { ... }
public boolean onMenuItemSelected(int featureId, Item item) { ... }
private boolean confirm(){ ... }
private boolean resetUI(){ ... }
private void fillUserUIfromDB(Long id) { ... }
       UserUI is always started by Login Activity. As mentioned before, it receives an
extra value: if it is equal to -1, means that user is going to input a new user (and the user interface
have not to be filled with any value, except for the contact list) else, an existing user is going to be
modified. The extra value is obtained in the onCreate method.

protected void onCreate(Bundle icicle) {
        this.userDB = new UserDBAdapter(this);;
        // extra values are embedded into Intent
        Bundle extras = getIntent().getExtras();
        userID = extras.getLong(UserDBAdapter.KEY_ID);
        if( userID != -1 ){
                // user exists and user interface is filled
} and User Activity layouts

       Login and User layouts are defined in two different XML files. Both are accessed from the
Resource class.
The following code sums up the user.xml file, which defines the UserUI Activity layout.

<ScrollView [...] >
        android:id="@+id/user" [...] >
                android:id="@+id/contactlabel" [...] />
                android:id="@+id/user_contact" [...] />
                android:id="@+id/usernamelabel" [...] />

                android:id="@+id/user_username" [...] />
                android:id="@+id/passwordlabel" [...] />
                android:id="@+id/user_password" [...] />
        Cause of mobile phones are small screen devices, all controls for confirming or cancelling
are placed in the menu: as result, screen is always showing information. Moreover, this structure
enables the developer to use a single method, in this case onMenuItemSelected, to keep track
of user decisions, making the “controller” section of code light and maintainable.

2.3.2. Accounts and Account Activities Activity

        AccountsUI class extends ListActivity class. This type of activity is suitable when
it is necessary to show a list of items. The ListActivity class provides a method called
setListAdapter: it automatically binds data contained into an Adapter (a
SimpleCursorAdapter, an ArrayAdapter or a custom one) to the main user interface
component, the ListView. This class structure can be evaluated in the following code.

public class AccountsUI extends ListActivity {
// Fields
// Omitted menu ID constants
private UserDBAdapter userDB;
private AccountDBAdapter accountDB;
private Long userID;
// Methods
protected void onActivityResult(int requestCode, int resultCode, String data, Bundle extras) { ... }
protected void onCreate(Bundle icicle) { ... }
protected void onListItemClick(ListView l, View v, int position, long id) { ... }
public boolean onCreateOptionsMenu(Menu menu) { ... }
public boolean onMenuItemSelected(int featureId, Item item) { ... }
public boolean createAccount() { ... }
public boolean editAccount() { ... }
public boolean deleteAccount() { ... }
private void refreshUI() { ... }
public boolean viewMails() { ... }
      This Activity retrieves data from the SQLite database using the accountDB object.
The onCreate method constructs the accountDB object, the userDB object (which obtains
username and user id) and resets the user interface. The menu is similar to LoginUI

        createAccount and editAccount methods are implemented with the same
“protocol” used for communicating between LoginUI and UserUI objects.
        The most important difference is that User interface is filled without iterating any data
structure. All the work is performed by setListAdapter: it requires a CursorAdapter
        SimpleCursorAdapter object is built using:
    • Activity Context
    • Resource layout of the list row: an XML file, containing the layout of a single row of
        the list must be placed in res/layout folder. This layout will be automatically repeated
        for each entry of the list
    • A Cursor pointing to a database record set
    • A String array, containing the table column names to project on screen
    • A int array, containing the “destination view” ids.
The String and int arrays must be of the same length.
        The code necessary to refresh user interface and update the account list is listed below.

private void refreshUI() {
        Cursor uC = userDB.fetchUser(userID);
        // accounts are fetched from the SQLite database
        Cursor asC = accountDB.fetchAllUserAccounts(userID);
        // “from” contains columns to show on screen
        String[] from = new String[]{
        // “to” contains the layout resource ids of the destination row view textviews
        int[] to = new int[]{
        // SimpleCursorAdapter gets as second parameter the layout resource of row view
        SimpleCursorAdapter accounts =
                new SimpleCursorAdapter(this, R.layout.account_list_row, asC, from, to);
        setTitle(getString(R.string.app_name) + " - " +

       The Activity layout is defined in account_list.xml file. ListActivity layout must
contain a ListView element. The ListView must be assigned the id value equal to
       Row layout is defined in account_list_row.xml file. In this case, it is implemented
by using a LinearLayout containing two TextViews for displaying account name and account
protocol type.
       The image on the top of the following page is a screenshot of AccountsUI Activity.

                                                 28 Database Adapter

       AccountDBAdapter is the twin of UserDBAdapter class.
There are similar methods for email account creation, update or deletion. A difference is made by
getAccount method: it returns an Account typed object. An overview of this class is given in
the next section of this document.
       The accounts table contains the following data.

Field label        Field type      Field properties                Description
_id                integer         primary key autoincrement       Table Primary Key
_uid               integer                                         User ID Key, act as external key
                                                                   and it references to a contact id
type               varchar(5)      not   null                      Account type (POP3 or IMAP)
alias              varchar(20)     not   null                      Account name
username           varchar(64)     not   null                      Account username
password           varchar(64)     not   null                      Account password
host               varchar(255)    not   null                      Account host domain or IP
port               varchar(6)      not   null                      Account server port
useSSL             integer                                         SSL Socket (0 or 1)
needSTARTTLS       integer                                         START TLS required (0 or 1) Class

        Account is an abstract class. The application is supporting both POP3 and IMAP
email accounts. Methods and fields used to implement both types of account are similar: the
Account abstract class provides a common ground.
        An interface provides a weaker relation: POP3 and IMAP account have common methods
and fields. Interfaces can be used only for methods.

public abstract class Account{
// Fields

protected String alias;
protected String username;
protected String password;
protected String host;
protected String port;
// Methods
        public Account(String alias, String username, String password, String host, String port) {
                this.alias = alias;
                this.username = username;
                this.password = password;
       = host;
                this.port = port;
        public abstract Folder open(boolean overrideSSL)
                                               throws NoSuchProviderException, MessagingException;
        public abstract boolean close() throws MessagingException;
        public abstract String getType();
        public String getAlias() {    return alias; }
        public String getHost() {      return host;   }
        public String getPort() {      return port;   }
        public abstract boolean isOpen();
      POP3Account and IMAPAccount classes extend Account. The following code is the
POP3 Account open method. IMAP version is similar.

public Folder open(boolean overrideSSLFactory) throws NoSuchProviderException, MessagingException{
// new Empty Properties
Properties props = new Properties();
// SSL Stuff
                                       "" );
        }else {
                props.setProperty("mail.pop3.socketFactory.class","" );
        // Prevents to fall into NOT-secure connection
        props.setProperty("mail.pop3.socketFactory.fallback", "false");
// Properties
props.setProperty("mail.pop3.port", port);
props.setProperty("mail.pop3.socketFactory.port", port);
// Session
this.pop3session = Session.getInstance(props);
// Store
this.pop3store = this.pop3session.getStore("pop3");
this.pop3store.connect(host, username, password);
// Folder
this.pop3folder = this.pop3store.getFolder("INBOX");;
return this.pop3folder;
       Both classes use JavaMail API (more information at
The JavaMail API provides a platform-independent and protocol-independent framework to build
mail and messaging applications. This API is under CDDL open source license. API porting

       There are different JavaMail API versions. The last one (1.4.1 version) was released on
October 2007. The latest versions requires JAF (JavaBeans Activation Framework), that is used by
JavaMail for determining which type of data is encapsulated into a message (detecting the MIME
       JavaMail supports many different messaging system implementations, message stores,
formats, and different message transports.
        It can be used as a monolithic JAR file, containing the whole library.
If there are not required features, the developer can import single modules. For example, a
programmer interested in enabling his application to send messages, should import the base classes
(that model the email message and server session, store and folder) and the SMTP JAR file (that
contains classes for email delivery).
        Mail Android is developed in Eclipse IDE. There were some problems when importing 1.4.1
version of JavaMail API. The issue was caused by IMAP classes: the project cannot be built due to
a “non existing class”. To the other hand, JavaMail 1.3 version could be imported without problem.
There are no major changes between the two releases, so the application development started using
the old version.
        The API seemed to work properly: both IMAP and POP3 allowed email download. There
were some problems in MIME message parts recognition.
        An internet message (as defined in RFC822 and MIME RFCs) can encapsulate different
types of data, such as plain text, HTML or images. JavaMail and JAF are designed to recognise the
MIME type of a message part and create the most suitable object.
For example, plain/text MIME type is handled using a String object, multipart MIME
type generates an object implementing Multipart Interface.
        When running on Android, the getContent method always returned InputStream
objects, which is default if a MIME type is not supported.
Exploring the sources of 1.4.1 version of JavaMail and 1.1.1 release of JAF, there were errors:
    • CommandInfo class needs java.beans package, which is not present in Android
            o This class is never used in Mail Android, so references to the missing package have
                been commented out
    • image_jpeg and image_gif classes are based on java.awt.Image; Android is not
        shipped with awt package
            o There is no similar Image class in Android packages. Images will be stored using
                InputStream object
    • CommandMap and FileTypeMap classes use external files or system interaction to
        retrieve respectively available command objects and data typing interface for files
            o Due to Android security policy, no file can be opened within a package or its folder:
                these entries have been added via code
    • DataFlavor class and Transferable interface are missing in Android
            o java.awt.datatransfer package (part of Apache Harmony SVN) has been
                included in project sources
    • There are different classes used to render images importing different awt package classes
            o awt dependant classes have been removed
        After these changes, Mail Android became capable of extracting most known MIME types
and handling them returning the right Object. Activity

       AccountUI activity is the counterpart of UserUI activity.

     The previous image is a screenshot of account activity. There is an input control
(TextViews, CheckBoxes and a Spinner) for each account table field.

2.3.3.Mails activity

       MailsUI Activity is implemented using a ListActivity. This time, the data
adapter is not binding data from a database, but from a Message typed list.
       It is necessary to write a custom adapter: for this purpose, was created the
FolderAdapter class, which extends BaseAdapter class.
FolderAdapter binds data from an object implementing a List interface to the ListView.
The List must contain objects extending Message abstract class.
       Message is a JavaMail class, which models an email message.


        Emails are retrieved from the server Folder. This operation can take up a considerable
amount of time, depending on network speed and the number of emails. In addition, running heavy
blocks of code within the main thread would make the system busy.
        The mail retrieving block of code is placed in a Thread. User interface is not accessible
from the Thread, so the android.os.Handler is responsible of receiving Runnables that
will do some stuff for it. These objects (implementing Runnable interface) call methods for
updating ProgressBars and the FolderAdapter.
The Handler builds a thread queue, for executing asynchronous instructions. Most important
instructions for email retrieval are listed below.
// Server folder is opened, the Progress Dialog is shown
retrievedFolder =;
mProgressStatus = 0;
// Cause of Folder opening could take up a lot of time, it is necessary to check if the user
// cancelled email retrieval during this period of time
if(retrievedFolder != null) {
        for(Message msg : retrievedFolder.getMessages()){
                        // Iteration is interrupted if thread is asynchronously interrupted
                // Only few elements of the Email message are obtained from the server
                mProgressStatus = 10000*msg.getMessageNumber()/retrievedFolder.getMessageCount();
                // A UI update request is sent to the Handler
       The image below describes asynchronous calls during email fetching.

       If an Exception is thrown by email fetching instructions, the human readable description
of this event is stored and exceptionOccurr flag is set. Both are used in the
mUIProgressEnd Runnable, which is responsible of showing error messages. Adapter

      The FolderAdapter class was written so that no iteration would be necessary for
showing the list of fetched emails. It is implemented using the following code.

public class FolderAdapter extends BaseAdapter {
// Fields
private Context context;
private List<Message> messageList;
private int rowResID;
// Methods
public FolderAdapter(Context context, int rowResID, List<Message> messages ) {
        this.context = context;
        this.rowResID = rowResID;
        this.messageList = messages;
public int getCount() {        return messageList.size(); }
public Object getItem(int position) { return messageList.get(position); }
public long getItemId(int position) { return position; }
public View getView(int position, View convertView, ViewGroup parent) {
        Message message = messageList.get(position);
        ViewInflate inflate = ViewInflate.from( context );
        View v = inflate.inflate( rowResID, parent, false, null);
        try {
                // View element ids are fixed
                TextView mailSubject = (TextView) v.findViewById (;
                mailSubject.setText( message.getSubject() );
                TextView mailFrom = (TextView) v.findViewById (;
                mailFrom.setText( message.getFrom()[0].toString() );
        } catch (MessagingException e) {
        return v;

2.3.4. Mail activity

        As the other activities of this application, MailUI Activity receives the mail id, provided
by the Mails activity Intent.
        Threading is used for retrieving selected email, but this time the UI is not updated. An
indeterminate ProgressDialog is shown.
        The core of this Activity is the LocalMessage class. It acts as a wrapper for objects sub
classing Message class. class and LocalMessageElement interface

       LocalMessage class performs the following operations:
   •   it fetches From, Subject, Sent date, Received date and Size from email header
   •   recursively extracts email parts (as well Multiparts)
            o in case of inline sections, an Inline object is allocated and added to an internal
               Map (typed String – LocalMessageElement)

          o in case of attachments, an Attachment object is allocated and added to the internal
          o nested emails are also supported
   • All LocalMessageElements are written on the sdcard drive
The Java code necessary for extracting Parts from Message object is listed below.

// Recursively extracts Part/Multipart elements from Message
private void recursiveExtract(final Part part) throws MessagingException, IOException {
        String disposition = part.getDisposition();
        if( part.getContent() instanceof String) {
                if( (disposition == null) || disposition.equalsIgnoreCase(Part.INLINE) ) {
                        LocalMessageElement inline = createInline(part);
                        this.contents.put(inline.getContentId(), inline);
        if( part.getContent() instanceof Multipart ){
                Multipart mpart = (Multipart) part.getContent();
                for( int mpc = 0; mpc < mpart.getCount(); mpc++ ){
                        Part tempBP = mpart.getBodyPart(mpc);
        Attachment attachment = createAttachment(part);
        this.contents.put(attachment.getContentId(), attachment);

        Both Inline and Attachment classes are implementing LocalMessageElement
        LocalMessageElement interface is useful for providing the user the list of email Parts.

         WebView components is capable of rendering rich content data, such as text files, images or
HTML code. The loadUrl method provided by this type of View loads a given URL.
         The sdcard drive can be accessed by the WebView using the file://sdcard/ path.
If the email has been downloaded and all Parts have been written properly, a Spinner component
is filled with the list of inline and attachment elements.
         The user selects the email section to be rendered.. and DummyTrustManager classes

        Email providers, in the last years, offer a secure access to email folder.
Security is implemented by using SSL and Certification Authorities. JavaMail supports both of
them: the package is shipped with default classes created for this purpose.
        If a mail server (IMAP or POP3) is using a Certificate which was created by a not trusted
organization, the mail Folder is not accessible.
        DummySSLSocketFactory and DummyTrustManager classes let the user to access
and retrieve emails even if Certificate is untrusted. These classes perform no check.
The menu contains a control that switches SSL override mode.
        The following image represents a MailUI screenshot when email contains an HTML page.

       It is possible to zoom (in or out) the WebView content or follow external links, which will
be opened in the Android built-in browser. Browser opening will send Mail Android in background.

        Mail Android could be improved both in performances and features.
Here is presented a list of possible features to be implemented:
   • Store user preferences in a database
   • Change Folder access implementation: the main idea is to launch a POP3 or IMAP
        service which runs in background. This service stores emails in a database, synchronizing
        remote and local Folders. It could also notify incoming messages in the status bar.
        Email database is wrapped up by a ContentProvider, which allows other applications
        (granted with a specific permission), to get email content.
   • Advanced email synchronization

2.5.Android lacks
       During Mail Android development, there were some missing features or issues:
   •   Android is missing an easy for transferring complex Objects between Activities.
       Only primitive data types can be ContentProviders are a great idea but need time to be
            o A object oriented database could be useful for this purpose, but embedded devices
               are not a suitable environment
   •   It is hard to follow MVC (Model-View-Controller) architectural pattern: user interface and
       “controller” code are tightly coupled
   •   Android Documentation is sufficient but a verbose version would be appreciated (more
       examples needed)

   •   Android is Open Source, but sources have not been released (except for some packages)

2.6.Testing and debugging
       Mail Android has been tested with different mail accounts (both IMAP and POP3 ones).
This kind of applications should be tested releasing them firstly as alpha version (addressed to other
developers or experienced users) and later in beta version. The beta release could be useful for the
developer if users can send feedback or bug reports.
       The image below is an emulator screenshot: retrieving mails when receiving an incoming

       Android tools include the Dalvik Debug Monitor Service: it is highly integrated into Eclipse
IDE, providing some useful stuff.
The DDMS is a tool which allows:
   • Control of multiple emulated devices
   • To change emulated device behaviour (network speed and delay)
   • Simulation of telephony actions (such as incoming calls or SMS)
   • File system navigation
   • File download (from device) and upload (to device). sdcard emulation is required
   • Thread monitoring
   • Heap statistics
   • LogCat, an advanced logging tool. It can be used by importing android.util.Log in a
       specific class and use the Log.e, Log.w, Log.i, Log.d, and Log.v methods for
       printing to log respectively ERROR, WARN, INFO, DEBUG, VERBOSE messages

The emulator shipped with Android SDK can simulate different types of devices (HVGA or
QVGA, both in vertical or horizontal orientation).
      The following image shows the DDMS graphical user interface.

2.7.APK package creation
      The project package includes Sun JavaMail sources. The following image represents the
package structure.

Written source code consists of:
   • 18 Classes
   • 1 Interface
   • 8 XML Layout files
   • 1 XML Strings file
   • AndroidManifest.xml file
   • Approximately 1900 lines of Java code
   • 24 icons for menu items (Mark James under Creative
        Commons Attribution 2.5 License)
The redistributable APK file can be created by using Android                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Tools                                                                                                                                                                      –                Export
Application Package.

2.8.Learning curve and Android framework learning time
       Mail Android developing and Android environment analysis took up more or less 120 hours.
Most of time was spent searching on the internet, exploring Android class hierarchy or analysing
       The amount of 120 hours is an estimated value. Community and developer groups play an
important role when documentation is missing.
       Experience and knowledge increases as a result of writing different kind of Activity classes
or even extending Android package classes.
       Approximately 30 hours were used for testing and debugging.
       I tried to draw a graph showing a sort of personal “learning curve” during time. It also
includes research on JavaMail API.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Thread improvements and Fifth activity implementation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Sixth activity, Textview implementation
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         Third and fourth activity implementation
            Java and OOP knowledge

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Fifth activity implementation
                                                                                                                                                                                                                                  Mail Android project creation and first activity implementation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      JavaMail web searches due to issues and sources exploration
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    JavaMail analysis

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      GUI improvements
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       LocalMessage class implementation (improved)

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Raw code blocks removal and Android documentation exploration

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Code reviewing and testing
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         sdcard emulation and first file writing attempt
                                                                                                                                                                                                                                                                                                                                         Second activity

                                                                                                                                                                                                                                                                                                                                                           Communication between activities

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   Minor improvements
                                                                                                                                                  First attempt to create an example application from scratch

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Code refactoring
                                                                                                                                                                                                                                                                                                                                                                                              Account (POP3 and IMAP) classes implementation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           LocalMessageElement interface implementation
                                                                                                                                                                                                                                                                                                                       Intent analysis
                                                                                                                                                                                                                                                                                                    Database Adapter
                                     Android documentation exploration

                                                                                                                                                                                                                                                                                                                                                                                                                                               ListView analysis and implementation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Menu analysis and implementation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        First attempt to open Folder and threading implementation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          WebView used for displaying email content
                                                                                                                         Mail Android scratches

                                                                                                                                                                                                                Layout examples
                                                                         Android SDK tutorials

                                                                                                 Android SDK tutorials

         Copyright (c) 2008 Luca Belluccini.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU
Free Documentation License, Version 1.2 or any later version published by the Free Software
Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy
of the license is included in the section entitled "GNU Free Documentation License".

Bibliographic citations
   •   Google – Android official website –
   •   Wikipedia articles –
   •   Yunhe Shi, David Gregg, Andrew Beatty, M. Anton Ertl – “Virtual Machine Showdown:
       Stack Versus Registers” –
   •   Frank Ableson – “Develop Android applications with Eclipse” –
   •   Dalvik VM Insights –
   •   Sun Microsystems – “JavaMail Design Specification 1.4” –


Shared By: