50
INSTITUT F ¨ UR INFORMATIK DER LUDWIG–MAXIMILIANS–UNIVERSIT ¨ AT M ¨ UNCHEN Fortgeschrittenenpraktikum Location-Based Services on the Android Platform Markus Mauder

LBS for Android

Embed Size (px)

Citation preview

INSTITUT FUR INFORMATIKDER LUDWIG–MAXIMILIANS–UNIVERSITAT MUNCHEN

Fortgeschrittenenpraktikum

Location-Based Serviceson the

Android Platform

Markus Mauder

INSTITUT FUR INFORMATIKDER LUDWIG–MAXIMILIANS–UNIVERSITAT MUNCHEN

Fortgeschrittenenpraktikum

Location-Based Serviceson the

Android Platform

Markus Mauder

Aufgabensteller: Prof. Dr. Claudia Linnhoff-Popien

Betreuer: Dr. Axel KupperPeter Ruppel

Abgabetermin: 19. Marz 2009

Hiermit versichere ich, dass ich das vorliegende Fortgeschrittenenpraktikum selbstandigverfasst und keine anderen als die angegebenen Quellen und Hilfsmittel verwendethabe.

Munchen, den 15. Marz 2009

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .(Unterschrift des Kandidaten)

Abstract

In 2007 the Open Handset Alliance unveiled a new mobile platform. This platform, calledAndroid, is set to become an important player in the mobile arena. It has several newcomponents, which make it ideally suited for the development of location-aware software.

This paper evaluates the Android Platform in the context of location-based services us-ing the pre-release SDK version m5. The project consists of building a piece of softwareas an example of a typical location-enabled product using the recommended developmentapproach. This document describes the resulting application, the development paradigm onthe Android platform and any problems encountered.

vii

Contents

1 Introduction 11.1 Existing Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Goals of the Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

2 Current Research 32.1 Issues with mobile messaging . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

2.1.1 Connectivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32.1.2 Bandwidth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42.1.3 Energy consumption . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2.2 Availability of location data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

3 The Android Platform 73.1 Existing Platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

3.1.1 Java Location API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73.1.2 Location Acquisition API . . . . . . . . . . . . . . . . . . . . . . . . . 8

3.2 The Android Platform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83.2.1 Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83.2.2 Location-based Services . . . . . . . . . . . . . . . . . . . . . . . . . . 123.2.3 GTalk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

3.3 Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

4 Location-Based Services on the Android Platform - GeoBoxing 154.1 Scenarios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154.2 Use-Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164.3 Usage of Android technologies in GeoBoxing . . . . . . . . . . . . . . . . . . . 17

5 Realization 215.1 GeoBoxing components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

5.1.1 Friend system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215.1.2 Message system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215.1.3 Friend positions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

5.2 Implementing Common Functionality on the Android Platform . . . . . . . . 235.2.1 Writing ContentProviders . . . . . . . . . . . . . . . . . . . . . . . . . 235.2.2 Implementing a proper Activity Lifecycle . . . . . . . . . . . . . . . . 255.2.3 Using implicit Intents . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

6 Evaluation 316.1 Extensibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316.2 A mobile operating system . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316.3 Proven technology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

ix

Contents

6.4 Developers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326.5 State of the Android . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336.6 Extensibility of the GeoBoxing application . . . . . . . . . . . . . . . . . . . . 346.7 Lessons learned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

7 Summary and Conclusion 35

List of Figures 37

Bibliography 39

x

1 Introduction

On 5 November, 2007 Google unveiled the Open Handset Alliance and a developer preview ofAndroid, their new mobile device platform. [Rub07] Android provided a number of features,which were not common on other platforms such as peer-to-peer messaging, database baseddata storage and a built-in location APIs.

This project will explore the Android platform by building a location-based applicationutilizing Android’s unique features.

Due to the unfortunate decision by Google to remove a piece of Android’s API, which isheavily used by the project, which was built to evaluate Android, the resulting applicationcould not be tested on a real device. Instead the emulator supplied by Google as part of theAndroid SDK has been used for testing.

To begin, we will take a look at a few existing projects. They are samples of some existinglocation-based service applications and are as such not entirely dissimilar from the projectthat will be built using Android.

1.1 Existing Applications

Most existing location-aware applications use location data to augment their functionality.They are not centered solely around being location-aware. Frequent uses are for exampleroute planning, showing the user’s current position and possibly annotation of other data(such as photos) with location information.

One example of an application augmenting information with location information is blog-ging about real-world events. Blog posts created with location-aware software are automat-ically annotated with the location at which they were written, connecting the post and theblogger with others close by. This phenomenon is dubbed moblogging (mobile blogging)[Wik08]. One piece of software supporting moblogging is CellSpin1.

Another application which adds location information is annotation of images with thelocation at which they’ve been taken. An example of this kind of application is Yahoo!ZoneTag2.

When choosing the objectives of our project, we were not satisfied with yet another ap-plication using only little context data. Instead the resulting applications makes locationan integral part of an activity. One popular application adhering to similar goals is Loopt3.It traces the user’s friends, allowing him to chat with them and share location information.Another application in the same category is Geominder4. Geominder allows users to createlocation-based reminders, which stay attached to physical locations. This is similar in scopeto the example application developed to test the Android platform.

1http://www.cellspin.net/2http://zonetag.research.yahoo.com/3http://loopt.com4http://ludimate.com/products/geominder/

1

1 Introduction

There are obviously a large number of applications, which use location information. Some,which might have been covered here include:

Mologogo is pretty similar in scope to Loopt. It shows your friends on a map or on theweb.

Plazes5 shows you where your friends have been, allowing to share pictures of the placesyou have visited.

gypsii.com6 automatically geo-tags audio and images and allows the user to find people andplaces close to his location.

ipoki.com7 is another application publishing the user’s location. It likens itself to a mobilesocial network.

1.2 Goals of the Project

This project was intended to test out the Android platform. It is to be expected that Androidby the sole fact of being newer will have profited from experience gained from other mobileplatforms and should be easier to work with than the current mobile platforms.

Special emphasis will be applied to building location-aware applications on the Androidplatform. In early preview-SDKs Android provided built-in peer-to-peer messaging capabil-ities. It was decided to make this an integral part of the application as this feature was setto become distinctive of Android. Unfortunately, this feature was among a small number ofAPIs, which were removed from the final SDK. The application still uses this API, becausethe project had been completed before this change was announced. An unfortunate effect isthat the final application cannot be run on the first devices shipped with the official Androidsystem. Android also has a different approach to structuring applications than the majorexisting mobile platforms, which will also be utilized as much as possible in the project. Tocombine all these capabilities, a project was chosen for its ability to use location-awareness,peer-to-peer messaging and as many unique features of Android as possible.

See 3.2 for a detailed description of the Android platform and 4 for a description of theimplemented application and the motivation for choosing it.

5http://plazes.com6http://www.gypsii.com/7http://www.ipoki.com/about.php

2

2 Current Research

Mobile devices have reached maturity in many areas. Today mobile devices have capabilitiestraditionally reserved for fixed devices. Mobile platforms such as Android attempts to pro-vide have increasingly made use of these capabilities as well as additional features providedby the mobility of current handsets to provide new services, which had not been possiblebefore.

Some issues inherent to mobile devices are currently in the process of being researched.Among these are ways to minimize the impact of mobile devices’ weak points such as unstableconnectivity and dependence on batteries for power.

2.1 Issues with mobile messaging

Android originally planned to include a system for peer to peer messaging between devicesrunning Android. The ability to send peer to peer messages through a mobile network is anon-trivial problem. Several integral characteristics of mobile connectivity make implement-ing these capabilities particularly hard. There was no information about how the Androidimplementation should have worked, but network issues were not among the official reasonscited for Android’s dropping of peer to peer messaging [Mor08]. However these issues appearmuch harder to solve than the reasons listed.

The following paragraphs discuss the issues mobile messaging is facing in addition to theissues known from traditional networks.

2.1.1 Connectivity

Mobile devices cannot assume permanent connectivity. Incomplete infrastructure, unsolvedissues with vertical handovers even if infrastructure were available, as well as interruptionsby the environment caused by movement of the mobile device into buildings or under groundare some reasons why connectivity might be interrupted at any time.

Connection oriented services, which are common on the internet today, are not designed towork under these circumstances. They assume that once a connection on the application layeris established, it can be used to send messages to their partner at any time. They especiallydo not expect their partner’s IP address to change. The first assumption is reasonableon a fixed network, where nodes only rarely disappear from the network. Wired networkcomponent do not face the volatility of a mobile network. The second assumption is part ofthe architecture of the Internet. Given that IP addresses change only rarely, the need for amechanism to work around this issue has not been pressing.

One solution to the connectivity problem was proposed by Machin and Dominguez in[AM08]. While not primarily intended to solve the connectivity problem, it proposes anarchitecture, which makes the device addressable even when it is currently offline. It triesto solve the connectivity issue through the concept of a push-gateway. The push-gatewayis a server on the internet, to which the mobile device maintains a persistent connection

3

2 Current Research

whenever possible. If the connection is broken, the mobile device re-establishes it as soonas it regains connectivity. Services wishing to connect to the mobile device connect insteadto a URL on the push gateway. They can then use well-established REST principles tointeract with the device. The gateway notifies the device over their persistent connection ofany incoming events and relays data from the device to the connected node.

To keep the connection alive the push gateway pings the mobile device periodically. Itutilizes XMPP or Comet to notify connected partners of mobile generated events. Usingthis method mobile devices can adhere to all REST principles and provide the illusion ofalways-on connectivity. The downsides of this approach are that devices on the internetcannot simply connect to an IP to establish a connection with a mobile device and thatservices on the mobile device are limited to services, which the push-gateway is capable ofrelaying to them.

Another solution to the connectivity problem is mobile IPv6 as defined in IETC RFC3775 ([DJ04]). Mobile IPv6 is an IPv6 protocol allowing devices to change their link whileremaining reachable by their home IP address. It can be used to sustain reachability of amobile device while it moves through a heterogeneous network. While there is a specificationfor mobile IPv4, this method requires special equipment. Mobile IPv6 has been picked fordepiction here because of its relative elegance and likely future adoption.

Mobile IPv6 employs the use of a home address. This is an IP address in the mobile device’shome link where a mobile device’s home subnet prefix is defined. If the device is away fromhome it gets a care-of address in another network’s link where it is then reachable in additionto its home address. On the node’s home link a home agent receives data addressed to themobile device and tunnels it to the node’s care-of address. A second mode of operationallows the mobile device to make its care-of address known to its corresponding node, whenanswering a request. The corresponding node can then address the mobile device directlyat its care-of address, thus avoiding additional routing and possible congestion at the homelink.

This solves the connectivity issue by making the device reachable through a unique homeaddress. Anytime the device is connected to the IPv6 internet it is immediately reachablethrough a known IP address. This solution is more elegant than the one described before,because the mobile device’s partner does not need to know that it is communicating with amobile device. Its downside is that with the currently low spreading of IPv6 the preconditionsfor its adoption are not yet met.

2.1.2 Bandwidth

The air interface is a scarce resource if only because flat rates for wireless access are not yetcommon. Mobile messaging may not be too verbose to avoid utilizing too many resources.Many contemporary messaging systems such as XMPP propagate a large number of events.For mobile devices many of these messages would be negligible. To them every unnecessarymessage is wasted bandwidth. Another issue with XMPP-based messaging protocols is theirreliance on an XML-inspired protocol, whose use of tags and plain text causes additionaloverhead. To remedy this short-coming there exists an XMPP extension, XEP-0138 ([JH07]),which details a method to compress XMPP streams.

A related problem is latency. TCP initialization can take up to 15 seconds on a 3G network[AM08]. The push-gateway solution to the connectivity problem presented above operateson a single persistent connection between the gateway and the mobile device. This would

4

2.2 Availability of location data

neatly solve the necessity to establish new connections between a node and a mobile deviceto push notifications.

2.1.3 Energy consumption

Mobile devices are constrained by the amount of energy they can carry. Many data operationsdrain the available energy. It is therefore advisable to minimize the number of data transfersrequired in mobile messaging and to keep the amount of data to send as small as possible.

2.2 Availability of location data

In the last two years many mobile devices have gained the ability to determine their currentlocation. This has been spurred in part by falling hardware prices for GPS modules. In theUSA and Japan legislation mandating the ability to provide a location fix on any user incase of emergency has accelerated the adoption of technologies for network-based positioningto be able to provide A-GPS location fixes. These technologies can now be used to providelocation-based services for users [Net08].

In its original incarnation GPS suffers from limitations, which can compromise the viabilityof location-based services. The requirements posed to any location acquisition technologyinclude time until location data is available and availability. Assisted GPS (or A-GPS) solvesthese issues by assisting the sensors built into the mobile device through communicationswith a provider of location data on the network.

There are several ways how a mobile device can be assisted by another party. By supplyingrough location data (for example through a database of the locations of cellular network cells)or the current time a server can supply information required for the mobile device to narrowthe search range for absolute codephases or the relative codephases once a signal has beenacquired. This enhances both the availability and acquisition speed of location data. If theCarrier-to-Noise-Ratio of the satellite signal is too low, data which is not location specificcan be supplied through the network by a device with a clear line-of-sight to the satellitethus enhancing the availability of location fixes under these conditions. It is theoreticallypossible to perform some of the calculations involved on a server and relieve the mobiledevice of this responsibility. While this has the potential to allow simpler devices to acquirelocation data this restriction is not commonplace on modern devices [Bry04].

5

2 Current Research

6

3 The Android Platform

The Android platform is one of the newest entries into the mobile operating system space.There are already a number of other platforms competing for market share in this area,which offer their own solutions to issues Android is faced with. Let us first look at thelocation-based services capabilities some of today’s major players offer.

3.1 Existing Platforms

As described in 2.2 many mobile device today include technology to retrieve location data.To make use of this information the major mobile operating systems have added support forthese technologies. They have introduced APIs to abstract the hardware specifics and makeit easy for end user applications to offer a consistent experience across a range of devices.

To illustrate the state of the art two APIs are depicted in more detail: Java Location APIand Symbian’s Location Acquisition API.

3.1.1 Java Location API

The JSR-179 Location API for J2ME is a J2ME Optional Package, which provides a genericway for resource limited devices to access their present geographic location. It is an abstrac-tion of any kind of underlying location retrieval mechanism. Possible candidates could besatellite based systems such as GPS or cellular network based methods.

It allows objects to get a LocationProvider instance, which fulfills a given set of require-ments as closely as possible. These requirements are set using a Criteria object. Suchrequirements might be accuracy, response time, power consumption, cost, ability to showspeed and course, ability to show altitude or the ability to determine the current address.

The Java Location API provides a Location object, which contains at least a valid latitudeand longitude as well as information about the accuracy of these values. If possible a locationprovider should also support altitude, accuracy of altitude, course and speed, textual addressinformation, landmark proximity events, orientation of the terminal as well as pitch and rollof the terminal.

By implementing a LocationListener the device can be periodically notified about lo-cation changes. One unique feature of JSR-179 is an integrated landmarks database. Thisdatabase contains important points such as the user’s home or workplace. JSR-179 alsocontains a security system only allowing access to location information to processes whichare authorized to use them [Gro06].

Android has classes corresponding to Criteria, LocationProvider, LocationListenerand Location, each going by the same name. It seems closely modeled after JSR-179 inthat respect.

7

3 The Android Platform

3.1.2 Location Acquisition API

The Location Acquisition API (LAA, sometimes called Self Locate API) is an API usedin Symbian OS to provide location information to user facing applications. Symbian OSsupports GPS, cell-based positioning and A-GPS (since v9.3). In addition to LAA, java-capable Symbian devices also support JSR-179.

LAA supports Mobile Originated Location Requests (MOLR, location fixes requested bythe user), Mobile Terminated Location Requests (MTLR, location fixes requested by a peer)and Network Induced Location Requests (NILR, requested by the network for emergencyuse). Using LAA an application can request a specific positioning technology, define a setof criteria and allow the operating system to choose the positioning technology or use thedefault positioning technology.

Symbian OS uses a location server, location framework, and positioning technology mod-ule.

To retrieve location information, an application retrieves an RPositionServer object,which it can in turn use to get an RPositioner, which corresponds to a LocationProviderin JSR-179. Using that, the application can request a TPositionInfo object, containinginformation about the selected positioning technology or a TPosition object, containinginformation about the user’s current position at the time the location fix was obtained[Ltd07].

3.2 The Android Platform

The Open Handset Alliance’s Android platform attempts to capture a piece of the growingmobile market. A major selling point of Android’s over the currently dominating mobileplatforms is its focus on openness and reusability of application components. This opennessgoal is reflected in the platform’s design, which enables the replacement of every componentin the system with a different one. This includes applications the cellular provider haspre-installed onto phones it sells to its customers and applications shipped with Android.

3.2.1 Concepts

Android introduces a number of new concepts and makes use of proven concepts from otheroperating systems. The openness of the platform discussed above can be found in mostaspects of the design. Android applications are made up of a number of components, whichcan be re-used individually by other applications to handle data these applications do notnatively support. The mechanism to do this is called an Intent, components receiving anIntent are called IntentReceiver.

User visible components in Android are called Activities. All operations, which should stayrunning even if the Activity is no longer active are handled by a Service. Applications andServices are also started through Intents, making them inherently replacable. Applicationscan store data they have collected in a ContentProvider, enabling other applications toaccess, add to and modify them. These components are described in detail below [Goo08b].Note that Activities are also launched through Intents, but these Intents cannot be receivedby an IntentReceiver.

8

3.2 The Android Platform

Activity

Activities are foreground components of applications. If user input is required for an appli-cation it creates an Activity to handle the user interaction. Its intended use is to assist witha single, focused activity.

The creation of the user interface of an Activity is achieved by using a View. Every userinterface building block as well as the combination of user interface elements to a completeinterface is derived from a View. An Activity can make any View its user interface.

Activities are the only components of an Android application which can be displayed by theAndroid launcher and thus can be launched by the user. To start a background component,applications must register the desired component with an Intent (discussed below) or launchit from an Activity.

Activities are central to applications. They can start other Activities or Services tocomplete background operations through Intents, display Views and interact with Content-Providers to retrieve and store data. Androids interface is centered around the manipulationof data. An Activity which registers as a default method to manipulate data (Intent cat-egory DEFAULT described below) can be thought of as the main interface to an application[Goo08e, Goo08j, Goo08p].

Service

A Service is part of an application, which runs in the background without exposing a userinterface. In Android all operations inside an Activity will be stopped when the user exitsthe Activity. Thus any operations which should continue even when the Activity is no longeractive must be run in a Service. It is important to keep in mind that Activities and Servicesare not so strictly separated in Android’s operating system implementation. Both run inthe same process and even the same thread. Thus starting a Service to do background workdoes not absolve the programmer from having to watch out for blocking and CPU-intensivework, which should be handled by a child thread.

Services can stay running for indefinite amounts of time. Some services may run for longerperiods of time (for example a service to play music), others may do one well defined joband then exit. Such a service may be useful to handle asynchronous operations from anIntentReceiver, which cannot handle them itself, because it terminates upon return from theonReceiveIntent function and will not be around to answer an eventual call-back [Goo08k].

Services can be started from any running application. To realize communications betweenthe service and the application that launched it (which may not run in the same process) thecalling application can bind to the Service. Since Services are only started once in Android(even though their onStart-method will be called repeatedly – see 5.2.2) if a Service existsthe application is bound to the existing Service. To interact between Services and Activities,applications can use the Android Interface Definition Language (aidl), which allows them topass objects between processes [?, ?, Goo08k].

ContentProvider

A ContentProvider is another common component of Android applications, which providesan abstract way to save and retrieve information. Any process may store information in aContentProvider and any process may retrieve from it (security restrictions may apply). A

9

3 The Android Platform

ContentProvider is normally implemented as a wrapper around an SQLite database or oneor more flat files.

By using ContentProviders applications allow other applications to retrieve, add to andmodify data they have created. Similarly to intent resolution described below, the systemdetermines which application can handle a given type of data. The component doing thisis called the ContentResolver. The information identifying a ContentProvider is suppliedas a URI. The ContentResolver gets information about the type of data a URI specifies byquerying the ContentProvider responsible for it.

URIs can either specify an individual entry in the ContentProvider, if it knows about it, ora list of entries. An example of the use of a standardized interface for information retrieval isthe implementation of the ListView in Android, which can hook up to any ContentProviderand display its contents [Goo08i, Goo08a].

Intent and IntentReceiver

An intent is a way to start Activities and Services as well as cause operations to happen inresponse to a broadcast. Broadcast Intents can be answered by IntentReceivers, start Intentsare resolved to launch Activities and Services. However an IntentReceiver cannot respondto an Intent to start an Activity or Service, just as they in turn cannot receive broadcastIntents.

Implicit Intents are instrumental to Android’s openness goal. They allow an applicationto specify a goal it wants to accomplish without needing to know which installed applicationis best suited to the task. Android takes care of matching the intent to an IntentReceiver,which is capable of accomplishing the requested task, calling it and possibly returning datafrom it. This type of Intent is called an implicit Intent. It allows the user to replace anycomponent in an Android system with another. Put another way implicit Intents are a wayof performing late runtime binding between different applications [Goo08j].

The complementing type of Intent is called an explicit Intent. It can be used to callan IntentReceiver directly or specify the exact application to be started. This should beused to provide a consistent workflow within the same application. While activities can bestarted explicitly implicit intents are the preferred way to handle tasks in Android to allowapplications to replace installed components.

Components can define one or more sets of criteria they can handle by specifying Intentfilters. For example an activity may be an entry point into a contacts application and beable to list contacts (as that is what it does by default anyway). It would then specifytwo Intent filters: One making it a default action to use on multiple contacts and anotherflagging it as a launchable application component. Activities are matched to Intents atruntime by matching the Intent’s information to the set of Intent filters. Thus Intents andIntent filters can specify similar criteria. Implicit intents are then resolved at runtime byAndroid. The activity which fits all specified constraints will be called and handed the Intentto operate on. To be matched to an Intent, the component’s Intent filter must provide atleast the requested action, the type and all specified categories the Intent requested. Inaddition any matched Intent filter must also contain the category DEFAULT to indicate thatthe application it describes is willing and capable of being the default action used on thistype of data [Goo08j].

Intents and Intent filters can carry information about the category of task they want toachieve. Categories specify under which circumstances a component should be called. They

10

3.2 The Android Platform

include MAIN for activities, which are the main entry point into an application or LAUNCHERfor activities, which should be displayed in a launch interface. The category DEFAULT specifiesthat this Activity provides a standard interface to handle the specified data type.

To specify what data an activity can operate on, it supplies a data type. Intents callingthe activity can include the same data type to be matched to this Activity. Alternatively,an Intent may contain a ContentUri describing a piece of data, which resolves to a data typethrough its appropriate ContentProvider.

If an intent is supplied with the unique class name of a component it becomes an explicitintent. Explicit intents can, but do not have to, contain any of the other information tobe used by the called component. They are resolved by their component name, not any ofthe other supplied informations. All other information inside the Intent can be used by thereceiving application, which receives the intent when it has been resolved. Intents can alsocarry extras, a bundle of arbitrary Java basic types, which the receiving component can usefor its operation.

Intents can be understood as a minimal language allowing the applications to formulatesimple commands such as ”list all contacts”, ”call Zaphod Beeblebrox” or ”edit note 3”.This language can be extended by new applications at will by adding new categories, actionsand data types [Goo08j, Goo08k].

Notification

Android is comparatively multi-tasking focused for an operating system built to run on de-vices with limited resources. It is designed to be able to sustain several running applicationsat the same time. One risk inherent to this capability is forcing the user to take his attentionoff of the activity he is currently engaged in to react to an event in one of the other runningapplications. To reduce this risk, Android employs a set of unobtrusive notifications, whichapplications should be using to notify the user of an event. Android’s NotificationManagercan display a persistent icon in the status bar, which is always visible, turn on or flash LEDson the device or flash the backlight, play a sound or vibrate to alert the user who can thenchoose to respond to the notification and switch to the activity [Goo08h, Goo08g, Goo08c].

Permission

Android can stop an application from using capabilities it does not have access to. If anapplication wishes to make use of an action or data provided by a different application, itmust specify to use the permissions the other applications requires. Upon installing a newapplication the user is prompted to review a list of permissions the newly installed activitywishes to make use of to be able to assess the risk of a potentially harmful application. Forexample the user might get suspicious if a dialer application has the capability to access theGPS device [Goo08t].

Resources

Developing user interfaces often requires that a large number of attributes are specified tocreate the interface the developer imagined. This can quickly become a tedious exercise.Additionally, many lines of programming code do not lend themselves to be visualized, onelooses sight of the relevant aspects of the code. Common examples include layouts of user

11

3 The Android Platform

visible screens or animations. These issues are commonly solved by letting developers specifythe relevant information through other means and creating the code at compile time.

Android employs this technique. It includes facilities, which allow developers to specifythese attributes using XML-based or other more appropriate types of files such as bitmapsfor stretchable elements like buttons. Resources, which can be created in such a way, includeexternalized values (strings and numbers), bitmaps, stretchable images (for buttons andother user interface elements), animations, which can be applied to individual elements orwhole windows from inside the program, and layouts of views. This list is not exhaustive,but contains most important resources.

3.2.2 Location-based Services

Android has been specifically designed to create location-based services on top of it. There isa standard interface to access LocationProviders, which the device can use to get informationabout its current where-abouts. It also features a Google API to access and display GoogleMaps and geocoding as well as reverse geocoding.

Android includes the system service LocationManager, which allows the user to specifya set of criteria to return the most suited of the available LocationProviders. From theLocationProvider the application can get periodical location updates or it can request thatan Intent be fired when the device approaches a given location [Goo08s, Goo08m, Goo08n,Goo08o].

APIs for geocoding and reverse geocoding are also available to build LBSs with. It allowsan application to match an address to a location (geocoding) or vice versa (reverse geocoding)[Goo08l].

Another included component helping in the creation of location-based services on theAndroid platform is the built-in support for Google Maps. While not officially part ofAndroid (it is designated as Google API [Goo08r]) it has been included with the AndroidSDK from the first release. It allows displaying a map of a specified region on the device aswell as moving around and overlaying graphics on top of the map [Goo08q].

3.2.3 GTalk

The preview-SDKs of Android contained peer to peer messaging capabilities among someother ”Google APIs”, which were not part of the Android core system. Originally thesewere called XMPP after the open protocol they supported. In later SDKs the name waschanged to GTalk to indicate an upcoming change to the system, which would have madeit incompatible to vanilla XMPP implementations [Goo08d]. However, even the modifiedprotocol was dropped from Android shortly before the release of the final version 1.0.

The GTalk API allowed applications to get presence information about other mobile de-vices using the service, sending of data and text messages and setting the user’s own presencestate.

The project this paper is based on had already been completed when Google announcedthat GTalk had been dropped from Android. Whenever mentioned, information about theGTalk system refers to the version which appeared in the pre-release m5 SDK, which is thelast version this project was ported to.

12

3.3 Comparison

3.3 Comparison

Android’s location capabilities are comparable to those existing in other mobile platforms.The API for accessing them is so similar to the one provided by JSR-179 that any majorchange would have been a surprise. The only capability it lacks compared to other availablelocation APIs is a built-in POI database. Using a ContentProvider such a system could beeasily implemented. The GeoBoxing system asks the user for this information, but does notmake it available to other applications. A logical extension might be to extend this into aproper POI ContentProvider.

Intents do not have a correspondence in other mobile operating systems. They are one fea-ture, which sets Android apart. If properly utilized they may become powerful instrumentsto help the Android platform gain more polished applications quicker by re-using existingcomponents. ContentProviders are instruments to achieve the same goal as Intents and holdthe same promise for the platform.

Android’s split of applications into interoperating pieces gives the core system more flex-ibility in managing processes and thus saving memory and processor cycles. This feature isnot present in this form in other mobile operating systems.

Peer to peer messaging would have been another unique feature setting Android apart.The fact that it survived as part of Google’s extensions of the official Android core systemuntil it was dropped in the first beta version shows that Google did not remove this featurelightly. If it makes a reappearance in a later version and the problems detailed in 2.1 areresolved it may yet become a major selling point for the Android platform.

13

3 The Android Platform

14

4 Location-Based Services on the AndroidPlatform - GeoBoxing

Having introduced the components of the Android platform and other mobile platforms, thischapter describes the components of Android in a practical context. It shows how they canbe used to build location-based services by leading through the design of the GeoBoxingproject. GeoBoxing has been built as part of the same effort to evaluate Android that thispaper is a product of. This chapter shows how it makes use of the location-based servicesAndroid has to offer. A more implementation focused description of GeoBoxing will be givenin the following chapter.

To be able to provide a hands-on overview and evaluation of Android, GeoBoxing had tomake use of as many of these technologies as possible while maintaining a focus on location-based applications. The following scenarios illustrate the goals GeoBoxing tries to achieve.

4.1 Scenarios

GeoBoxing is an environment aware messaging application. Current messaging applicationsusually try to deliver messages as soon as possible. The user or sender of a message have noway to guarantee the relevance of the message, because the sender is usually not aware of thecurrent activity the receiver is engaged in. GeoBoxing attempts to remedy this short-comingby allowing users to send messages are tagged with information about an environment whichwill trigger a notification about the message. For this first version it was deemed sufficientto provide the ability to specify circumstances for the message in terms of time or place.Nevertheless the resulting application should provide enough flexibility for real-world usagescenarios. Here are some examples of how GeoBoxing could be used:

Tom has recently moved to a new city. Although he has found new friends quickly, hefrequently gets lost when trying to meet up with them. When the group decides to meetat yet another place Tom doesn’t know yet, Mary – an experienced member of the group –leaves Tom virtual bread crumbs to follow by marking important points on the way betweenTom’s house and the meeting place with messages directing Tom further along the way orre-assuring him that he is on the right track.

Frank is late on a report and frequently works long hours to finish it on time. His friendsrarely get to see him these days. To avoid letting himself get distracted, Frank has evenasked them not to invite him around for a while so he can finish his paper without feelingbad about not meeting his friends. Of course he could hang out with his friends when he hasdecided to call it a night, but most of the time his friends have already left their homes whenhe could contact them when he gets home. Frank’s best buddy Mike has begun sending himmessages about their meeting place for the night, which Frank receives only when he getshome in time.

Mark’s friend Kate is disappointed to get to see Mark only once or twice a year since theyhave taken on different occupations. She would like to make it easier for him to drop by

15

4 Location-Based Services on the Android Platform - GeoBoxing

while avoiding to make him see it as an obligation. She sends him a message to be displayedwhen Mark is close to her house, reminding him to come by if he has the time.

Ashley has been very busy with various work related activities lately. Since she has somuch on her mind she has begun missing appointments with her chess club, who meetat irregular intervals. To remind herself she uses GeoBoxing as an advanced note takingapplication, scheduling messages to be shown to herself two hours before each chess clubmeeting.

4.2 Use-Cases

To achieve the described scenarios users can choose from a number of activities to accomplishtheir goal.

Mary in the first scenario writes several messages to Tom describing sections of the way.To do so, she selects Tom’s entry in her friend list. In the context menu of this entry, shecan choose to send Tom a message. She selects this entry, causing a new application to popup, allowing her to enter a text and a number of criteria for when to display the message.First, Mary writes a message reminding Tom to get on his way. She chooses to specify somecriteria by pressing the Pick criteria button. There she is presented with the possibility tospecify an earliest and a latest time at which to display the message, as well as a combobox to pick a point where it should be displayed. Since they have decided to meet at eight,she picks today’s date and a time of 7.30 as the earliest time. She wants Tom to see themessage at this time, regardless of other circumstances, so she chooses Use these conditionsto finish this activity, which returns her to the composer activity. This is all she needs todo, so she tabs Send message there. To mark the first way point for Tom, she chooses SendMessage again. This time she picks select on map as the location to display the message at.To avoid confusing Tom by showing the message when he happens to pass one of the waypoints during the day, she again picks 7.30 as the start time. Back in the composer window,she just puts Turn left into the message field and sends the message. She repeats the laststep until she is satisfied that Tom will have no dificulties to get to their meeting on time.

To meet Frank as often as possible, Mike has made a habit of sending reminder messagesto Frank each time their mutual friends meet. He doesn’t know that it is possible to specifythe friend by picking a context menu entry, so he chooses Send message in the menu of themessage list. Compared to the way Mary has seen the composer view, Mike’s view is a bitdifferent: Underneath the recipient field another button allows him to Pick a friend. Thenext view he sees is in fact the friend list, where Mike taps Frank’s entry, which takes himback to the composer view with Frank’s name now filled in. To avoid distracting Frank,Mike chooses an end time for his messages, so they expire if Frank does not get home ontime to join them. To make sure Frank only receives the message when he is home, Mikeadditionally chooses the its location as at home, which is a coordinate Frank has saved tohis mobile device to designate his home.

Kate does not care when Mark visits her, she just wants him to come by more often. Soshe decides to mark her house as the notification point and adds a very nice message invitinghim around.

Ashley wants to send a message to herself. Since the system does not differentiate betweenher own and somebody else’s ID she can easily do so. Viewing the message list, she realizesthat she has never sent a message to herself before. So she presses the menu button and

16

4.3 Usage of Android technologies in GeoBoxing

chooses add friend. In the dialog she gets to see next she specifies the name for the newcontact (me) and enters her GTalk-ID [email protected]. If a contact with the name meexists, it is associated with her friend. To make it easier for Ashley a list of possible contactsis displayed when she has begun typing in the new contact’s name. If the contact does notexist, a new one is created. Upon pressing Save friend the new entry me shows up in herfriend list. She can now choose the send message-entry in her contact’s context menu andremind herself of the meeting two hours before it takes place.

4.3 Usage of Android technologies in GeoBoxing

As described in chapter 3.2 Android provides a number of supporting technologies to realizelocation-based services. The GeoBoxing project aims to build a location-based applicationand its scope was large enough to use all provided location-based services technologies. Thefollowing list re-iterates these technologies and describes how GeoBoxing uses them:

LocationManager Messages can be addressed to people as well as places. To be able toalert the user if he enters a location associated with a message, GeoBoxing utilizesthe LocationManager, which can broadcast an Intent if the user enters an area with aspecified proximity to a specified point.

Google Maps The user can specify the position the recipient of a message should be in whenhe receives the message. To be able to provide this functionality GeoBoxing shows aGoogle map allowing the user to pinpoint the desired location.

GTalk To pass the message to another user, GeoBoxing uses Android’s built-in peer-to-peermessaging capability provided by GTalk.

Additionally GeoBoxing constitutes a complete Android application. Thus it makes useof many Android specific technologies and architectures. Before we see in detail which partsof GeoBoxing utilize which Android components, let us take a quick look at how the mostimportant of these roughly cooperate so we won’t get lost in the details. There will be alonger and more illustrative description in section 5.1:

Messages are received by the FriendMessageReceiver and stored in the MessageProvider.The messages’ conditions are watched by the MessageService, which uses Android’s Loca-tionManager to schedule proximity Intents. Those in turn are caught by the MessageCon-ditionReceiver and turned into new schedule items or displayed through Notifications andthe ViewMessageActivity. Sending of messages begins with the SendMessageActivity, whichallows the user to input the message (in cooperation with the SelectMessageConditionsAc-tivity) and sends it. A list of friends and the data required to use GeoBoxing with them isstored in the FriendsProvider and can be displayed through the FriendListActivity, whichis for example used by the SendMessageActivity or can be run as a stand-alone applicationto provide a starting point.

Let us now take a closer look what each of these and the other components do in detail:

(Implicit) Intents As described in previous chapters Android applications can call otheractivities using implicit Intents rather than explicit calls as they are common on currentdesktop based systems. In Android applications can use implicit Intents to start otheractivities. This allows the application to be extended by other applications, which

17

4 Location-Based Services on the Android Platform - GeoBoxing

register themselves as being able to handle the same action on the same data type. Allactivities, which ship with this application, can respond to implicit Intents. Internallysome activities are started using explicit Intents, where it would jeopardize the userexperience if other activities were substituted.

ContentProvider Content providers store various kinds of data. In the GeoBoxing appli-cation content providers ensure that other activities can make use of the messagesand friends databases GeoBoxing creates. Messages are stored in a messages contentprovider and can be accessed by any activity on the device. This could for examplebe used by other applications to utilize the message service to schedule reminders forthem. Additionally if another application makes use of the GTalk service, it couldretrieve friends’ JIDs from the FriendsProvider or use their location as stored in theLocationProvider to enrich their own user experience.

FriendsProvider The FriendsProvider contains all known information about the user’sfriends except their location, which is volatile information and not in the scope ofa data store for personal information. This information is instead stored in thelocation provider explained below. The stored information in the FriendsProviderincludes the friend’s GTalk ID to send them messages or data over GTalk, per-missions which specify if this friend is allowed to receive location updates and acontent URI pointing to the contact this friend is associated with.

LocationProvider The LocationProvider holds location information received from theuser’s friends. This information includes their current position’s longitude, lati-tude, a content URI pointing to the contact of the friend this entry came fromand when it was retrieved, enabling the application to communicate to the userif this information is still reliable.

MessageProvider The MessageProvider allows access to all currently known messages.The information saved in this provider’s data store contains a place condition, astart and end time, the message text, its current status and the GTalk ID of thefriend who sent this message. In this first version of GeoBoxing messages are notdeleted when they have been viewed or contain impossible conditions. Insteadtheir status is set to expired.

Activities For user interaction the application uses Android Activities. Most of these are inthe tools package. The system provides a number of Activities for user interaction:

FriendListActivity The FriendListActivity shows a list of all known friends and pro-vides the ability to view their associated contact, edit their information, showtheir position, delete them or send them a message, each utilizing other activitiesdescribed here.

ManageFriendActivity To add or edit a friend, the ManageFriendActivity is used.MessageListActivity The MessageListActivity shows all messages ever received. It

also contains information about the conditions and the status of the message,indicating if it might yet be displayed to the user.

SendMessageActivity The SendMessageActivity provides a form to compose a mes-sage and start the SelectMessageConditionsActivity to specify conditions aboutwhen to display the message to the recipient.

18

4.3 Usage of Android technologies in GeoBoxing

PickLocationActivity The PickLocationActivity allows the user to pick a location.This is for example used in the send message activity to specify the locationcondition or to specify the location to be used as home or work locations.

SelectMessageConditionsActivity The SelectMessageConditionsActivity is used bythe SendMessageActivity to allow the user to pick the conditions under whichthe message will be displayed. This is one example of an activity, for which itdoes not make sense to start it independently. Thus it is not in the DEFAULT cate-gory. Additionally, to guarantee an undisturbed workflow, this activity is startedby an explicit Intent. The absence of an Intent filter belonging to the DEFAULTcategory guarantees that the activity cannot be resolved for implicit Intents.

ViewLocationActivity To show the location of one or all known friends GeoBoxingprovides the ViewLocationActivity.

ViewMessageActivity The ViewMessageActivity displays a message inside the Mes-sageProvider.

Services Another important part of the Android platform are services. GeoBoxing of coursealso uses services. One important service (the MessageService) for example is respon-sible to bring the message to the user’s attention at the right time and place.

CommunityService The CommunityService is responsible for bringing the system intoa usable state. It is started by any application relying on the GeoBoxing systemto be running. It bootstraps the system by starting all other integral services,such as the UserLocationService which informs our friends about our position andthe MessageService, which fires Intents when context conditions are met.

MessageService This service watches over all known messages and schedules Intents,which are to be fired when a condition the sender specified is met. It utilizes theMessageConditionReceiver to handle scheduled Intents and schedule new ones ifappropriate. Together with this receiver it forms the basis for the message notifi-cation infrastructure. The code these components share is stored in an additionalclass MessageConditions, which is the only class in the application, which is notderived from one of the previously discussed components of an Android applica-tion such as Activities or Services.

UserLocationService To receive updates the UserLocationReceiver needs a compo-nent, which finds a suitable location provider and schedules location updates forit to receive. This is what the UserLocationService does.

Additionally services are used in Android to allow IntentReceivers to handle complextasks. IntentReceivers are limited in their ability to respond to Intents, because theyare only alive until they return from their handleIntent-function. To handle tasks,which require a call back, IntentReceivers can start a service, which stops itself assoon as it has done its due. In the GeoBoxing-application one such services is theLocationUpdateService.

LocationUpdateService This service is started to send a location update to everyfriend, which is registered to receive them. It terminates after one update, waitingto be created again by the UserLocationReceiver.

IntentReceivers Being able to react to changes in the system is essential for an environmentaware application like GeoBoxing. Therefore it utilizes a number of IntentReceivers,

19

4 Location-Based Services on the Android Platform - GeoBoxing

which react to changes in the environment the application functions in. GeoBoxing’sIntentReceivers are:

FriendMessageReceiver The FriendMessageReceiver receives messages from friendsand stores them in the MessageProvider.

LocationUpdateReceiver The LocationUpdateReceiver receives updates about a friend’smovement and calls the FriendProvider to update the data store accordingly.

UserLocationReceiver The UserLocationReceiver receives updates if the user moved.It causes updates to be sent to the user’s friends, who are registered to receivesuch updates in the FriendsProvider.

MessageConditionReceiver The MessageConditionReceiver is started when conditionsscheduled by the MessageService are met. If all conditions are met it shows a no-tification. If only one condition is met it schedules another Intent to make surethe message is displayed at the appropriate time or expires the message if thespecified end time has passed.

DeleteItemReceiver The DeleteItemReceiver deletes the item specified by a passedcontent-URI. The intent filter associated with this receiver guarantees that itcannot be abused to delete data not created by GeoBoxing.

Notifications The notification system provides an unobtrusive way to alert the user. Inthe GeoBoxing application it is used to draw the user’s attention to messages, whoseconditions are now met.

The next chapter will discuss how these components work together to provide the userinterface and logic for the GeoBoxing system.

20

5 Realization

GeoBoxing is designed to use as many of Android’s unique (and otherwise) features toevaluate it as a possible platform for future projects. In addition it is to be easy to extend.To this end it utilizes components designed to make the system extensible where ever possibleand consist of source code, which can easily be adapted to serve as a basis for other projects.

One of Android’s features and one which distinguishes it from the dominant existing mobileplatforms is its augmentability. It is inherent in Android’s design for other applications tobe able to extend the functionality of the platform. This is most clearly visible in Intent andContentProvider, which have been described extensively above.

5.1 GeoBoxing components

To be extensible GeoBoxing strongly adheres to Android’s design philosophy. An importantaspect of this was to split the application in as many components with a concise role aspossible. To better understand the functionality of these components, they can be viewedas pieces of sub-systems operating in concert to create the desired user experience. Thesub-systems of GeoBoxing listed below are separated purely for illustration purposes. Thissplit is not reflected in the design. This chapter will describe these components as well assome of the challenges faced and how to implement common functionality on the Androidplatform.

5.1.1 Friend system

One imaginable sub-system is the friend system, which manages friend contacts. In essenceit provides a form of address book managing all information required for the GeoBoxingactivity to function. It consists of the FriendsProvider, FriendListActivity (shown in figure5.1) and ManageFriendActivity.

5.1.2 Message system

Another sub-system is the message system, which is composed of a receiver and an evalua-tion system. The receiver system reacts to GTalk events, which are evaluated if they containa message and are written to the message provider if that is the case. The evaluation systemconsists of the MessageService, the MessageConditionReceiver and MessageConditions. TheMessageService reacts to changes in the MessageProvider. If it changes, a new message hasbeen received or updated. In response to changes it re-evaluates the messages. If a newmessage arrives a MessageConditions object is created from it and intents are scheduled ifapplicable. If an intent, which has been scheduled like this, is broadcast, the MessageCondi-tionReceiver picks it up and reacts to it by scheduling a new intent, showing a notificationor expiring the message. Since this evaluation requires largely the same logic as the original

21

5 Realization

Figure 5.1: FriendListActivity showing possible actions on a friend

scheduling of the message, it too utilizes the MessageConditions class. The MessageCondi-tions class evaluates which intents need to be scheduled for the intents to be fired at theright time. If the MessageConditions object has been created in response to an intent, itchecks if there are conditions, which have not been met. Since the MessageConditions classis the only class controlling these intents it can rely on the order of intents it schedules: if amessage contains a time, it does not schedule a location proximity intent until the time hasbeen fulfilled. This means that messages with an associated location condition can only befulfilled by a location intent. Messages without location intents are shown as soon as the be-gin condition is fulfilled. Android can only handle schedule one time intent per application,so every time a time condition is met all messages must again be parsed to locate the nexttime intent to be scheduled. Activities to interact with this component of the applicationinclude the MessageListActivity, the SendMessageActivity (pictured in figure 5.2) and forspecifying conditions the SelectMessageConditionsActivity and PickLocationActivity.

5.1.3 Friend positions

Another sub-system of the GeoBoxing application are the friend positions. These haveoriginally been designed to allow a user to send a conditionless message as soon as the userenters a particular area. These conditions however only had a purpose when viewed from aclient-server angle: a server can store large amounts of points of interest, which could havebeen used to send messages to the client when it came close to one. However soon afterthe begin of this project, Google announced that it would drop the standardized XMPP

22

5.2 Implementing Common Functionality on the Android Platform

Figure 5.2: SendMessageActivity ready to send

as its peer to peer communications platform making it impossible to hook into the peer topeer system with non-Android devices. For this reason the server component has not beenwritten as part of this evaluation. However the ability to inform peers of one’s positionhad already been built into the system. An example application showing this feature inaction is the ViewLocationActivity (see figure 5.3), which shows the current last knownposition of any friend, who sends updates. This application is to be understood as a proveof concept, it is not particularly polished. To update other users of one’s own positionthe UserLocationService registers with a location provider to send update intents about theposition to the LocationUpdateReceiver, which then starts the LocationUpdateService toestablish the GTalk connection and send an update to every registered friend.

5.2 Implementing Common Functionality on the Android Platform

As one goal of GeoBoxing is to serve as a starting point for implementing other location-based applications it has been designed to cover all notable Android technologies. In thissection each common functionality is described and a way to implement it is illustrated withan example from the GeoBoxing application.

5.2.1 Writing ContentProviders

Content providers are Android’s means for storing and sharing information. Any applicationcan define one or a number of data types, which it knows how to handle. It can rely on

23

5 Realization

Figure 5.3: ViewLocationActivity showing the position of a friend. (Map data not showndue to missing support for Google Maps API keys in Android m5.)

existing content providers to store its information or can implement its own content provider,which holds data of this type.

Content providers supply mechanisms allowing standard retrieval mechanisms to work.Any activity or service can ask for data in a given format. Android will then figure outwhich content provider is capable of returning this information and forwards the request,handling all inter-process communication involved.

Implementing a content provider is a straight forward process. Although content providerscontain a great many functions, only a handful of them are interesting for normal use cases.

It is up to the developer to decide how data is stored in the content provider. Howeverthe interface specified by ContentProvider is reminiscent of databases in many respects.It therefore lends itself to being implemented using an sqlite database, which is suppliedby the Android system and supported through a number of helper classes. Another possi-bility is to use flat files. For simple cases such as configuration data Android supplies theSharedPreferences infrastructure, which is used in GeoBoxing for storing the user’s homeand work place.

A straight forward content provider is the LocationProvider class implemented for thepurpose of this study. Please refer to it for a complete usable example.

ContentProviders extend the class ContentProvider. The interface to a content provideris stored inside an embedded class inside the provider sub-package, holding all interfaces toproviders written with the same prefix to their unique names. It defines a set of constantsfor developers to use to access the content provider. These include a constant CONTENT URI

24

5.2 Implementing Common Functionality on the Android Platform

holding a URI to the data type this provider handles as well as constants mapping theinternal names of the attributes, which make up a tuple inside the database this contentprovider wraps. These URIs are composed of the name of the content scheme (content), theauthority identifying the provider (de.roffnoppe.mobile.locations for the location provider)and the path to the resource requested (locations). The resulting string uniquely identifiesthe repository from which you want to select information. If the user knows which tuplehe wants to retrieve, he can also append another identifier referencing the tuple directly byits numerical id prefixed by a number sign. Combining all the discussed components into aURI, we arrive at something like this:content://de.roffnoppe.mobile.community.locations/locations/#12

To retrieve a sub-set of the tuples contained in this repository the user can pass an SQL-style WHERE-string into the provider, which it must handle. This is called a selection below.

The class ContentProvider contains the following functions to implement this behavior:

query Queries the content provider, returning a cursor to the resulting set. The queryfunction can be passed a selection to filter the results by.

insert Inserts a tuple into the content provider.

delete Deletes a tuple from the content provider. This tuple may be directly referenced byits URI or selected through the use of a proper selection.

update Updates a tuple inside the content provider. Like the delete clause it can take aURI referencing a tuple directly or it can supply a selection.

The type of data stored in the content provider can be retrieved as well. To enable thisa content provider should implement the function getType. This functionality is used byAndroid to find a matching ContentProvider if an application does not specify one. Thisagain allows applications to use resources collected by other applications that didn’t evennecessarily exist at the time of development.

5.2.2 Implementing a proper Activity Lifecycle

Android has been written to be used on resource limited devices. As such it employs advancedtechniques to handle events of depleted resources gracefully. To hide the implementationdetails of suspending and resuming applications from the user, it allows developers to preparean application for being suspended and get it back into a working state upon being awakened.

The amount of event handler functions provided by Activity seems very large at firstsight. However, their purposes are clearly defined and easy to comprehend. To get theapplication off the ground all one has to do is implement the onCreate function to loadthe activity’s view. To support the user when the application is being stopped, we will alsowant to implement the onFreeze function to save the current state of the application. Ifour application does something resource intensive, which is only relevant when the user seesit, we may also want to implement onStop and onRestart to stop what we are doing whenthe user is not watching. Similarly when some work only needs to be done while the useris able to generate input, we may want to implement onPause and onResume. This maymake sense for a game. A more detailed description of these functions and when to use themfollows [Goo08f].

25

5 Realization

onCreate When an activity is created, its onCreate function is called, thus it is called onlyonce during the lifetime of a process. If the process is terminated or killed withoutbeing properly shut down through the onDestroy method, onCreate is passed a bundleof values originally produced by the onFreeze function to be able to recreate a previousstate.

onStart After the onCreate function, the onStart function is being run. This function isalso called again after the activity comes back to the foreground. In this case it ispreceded by a call to onRestart.

onResume Before the function enters its running state the onResume function is called. Herethe activity restores itself to the state it was in when onPause was called.

onFreeze When the activity is leaving its running state the onFreeze function is called.It allows the application to save all information required to re-establish the activity’scurrent state. After this function has been called it is possible that the application willbe stopped or killed at any time. If it is resumed at a later point the user should notnotice that the application was ever gone.

onPause After the onFreeze function the onPause function is called to indicate that theactivity is not currently focused anymore. After it comes back to the foreground followsanother call to onResume. onPause might be used to pause a game the user looses theability to make input to it.

onStop If the application goes to the background (i.e. it is no longer visible) its onStopfunction is called. When it is woken up from this state its onRestart, onStart andonResume functions are called.

onDestroy When the application is terminated without an immediate resource need (thenormal case), the onDestroy function is called.

As an example consider the SendMessageActivity, which is part of this project. It allowsthe user to compose a message to a friend. The activity is straight-forward: The user selectsa friend, a number of conditions to apply to the message and types a text to be displayedwhen the conditions are met. If this activity goes to the background and is killed because oflow resources, it must come up as if it had never seized running. For this purpose it needsto implement the onFreeze function and re-initialize itself in its onCreate function. As theactivity does not do any resource intensive work or does otherwise care that it is no longervisible to the user, it does not need to implement the onPause or onStop function as well astheir counterparts onResume and onRestart.

5.2.3 Using implicit Intents

One of the most important goals of Android is to make the components comprising thesystem replaceable. A technology, which is absolutely central to this goal, are implicitIntents. Generally speaking Intents are a kind of interprocess communication, whereby oneapplication can tell another to complete a given request.

In Android activities are not synonymous with applications. Each application can containa number of activities, services, content providers and IntentReceivers. Every application can

26

5.2 Implementing Common Functionality on the Android Platform

onCreate

onStart

to foreground

onResume

running

onRestart

onFreeze

onPause

looses focus

onStop

to background

to foreground

onDestroy

Figure 5.4: Activity lifecycle

27

5 Realization

ship with an IntentReceiver, which is capable of receiving the Intent sent by an application,which already existed before this application was developed. One application can start piecesof other applications to do jobs for it.

The practical advantage to the user is that he can replace functionality which existedpreviously in the system with that of a newly installed application.

To participate in this system an application can send and handle implicit Intents. Animplicit Intent can be composed of a number of different criteria, altogether specifying oneor more components in the system, one of which is then invoked and receives the request. Acommon way to specify an Intent is by specifying an action (i.e. what to do) and a piece ofdata. The Android system asks the known content providers whether they know the datatype of this particular piece of data. The thus acquired data type is matched against thecapabilities of all installed IntentReceivers as specified in each application’s manifest file.

To start an activity without specifying a concrete activity, you can do something like this:

In tent addFriendIntent = new In tent ( ). s e tAct ion ( Intent . INSERT ACTION). setData (Community . Fr iends .CONTENT URI) ;

s t a r tSubAct i v i ty ( addFriendIntent , 0 ) ;

The friend provider’s getType function returns the MIME-Type vnd.roffnoppe.cursor.dir/vnd.roffnoppe.friend. In the application’s manifest file we find the following:

<a c t i v i t ya n d r o i d : l a b e l=” @str ing / i m p o r t f r i e n d s ”android:name=” . t o o l s . ManageFriendActivity ”android:theme=” @andro id : s ty l e /Theme . Dialog ”><in tent− f i l t e r

a n d r o i d : l a b e l=” @str ing / i n s e r t f r i e n d ”><ac t i on

android:name=” android . i n t e n t . a c t i on . INSERT” /><category

android:name=” android . i n t e n t . category .DEFAULT” /><data

android:mimeType=”vnd . ro f fnoppe . cu r so r . d i r /vnd . ro f fnoppe . f r i e n d ” />

</ intent− f i l t e r>. . .

</ a c t i v i t y>}

This tells Android that our activity can handle the INSERT action on this data type.android.intent.action.INSERT is the value of Intent.INSERT ACTION used in the codesnippet above. The category DEFAULT allows this activity to be started in response to animplicit Intent. An intent filter like this specifies all criteria that must be met for this ac-tivity to be able to work with this data. Intent filters are not limited to activities but canbe specified for intent receivers as well.

An IntentReceiver is a piece of code, which can respond to an Intent which is not a callto start an Activity. They are used for background events and small actions, which do notrequire any user input. In this project IntentReceivers are for example used to respond to

28

5.2 Implementing Common Functionality on the Android Platform

location updates from friends, to save messages and to check whether a message conditionhas been met in response to a potentially interesting change in the environment.

To construct and send an intent to an intent receiver use something like the following,which instructs a content receiver to delete a message:

In tent de leteMessage = new In tent ( ) ;de leteMessage . s e tAct ion ( Intent .DELETE ACTION) ;de leteMessage . setData (

mMessageListAdapter . getMessageUri ( i n f o . p o s i t i o n ) ) ;b roadcas t In tent ( de leteMessage ) ;

29

5 Realization

30

6 Evaluation

Android is different from other mobile platforms. Most of the differences come down to An-droid’s focus on openness and extensibility of existing applications. Additionally, Android’sdesign shows a number of realizations of how the needs and capabilities of mobile devicescirca 2008 differ from traditional environments. Android achieves a compromise betweenperformance, the capabilities and limitations of mobile devices and ease of development.

Nevertheless Android has a learning curve. Unlike other mobile operating systems, An-droid establishes a different development paradigm, which will be unfamiliar to most new-comers to the platform. However, once developers have become used to the way Androidworks, it becomes obvious that the components of the system work well together and mostnovel concepts flow naturally from the larger design.

This chapter reiterates what sets Android apart from other platforms and evaluates howwell they succeeded, starting with Android’s most fundamental difference: extensibility.

6.1 Extensibility

Android is written to give the user more than average control over the environment he worksin. Every user facing component can be replaced. To allow this, Android uses the conceptof Intents. An Intent is broadcast by applications and Android resolves the request to anapplication, which does not necessarily have to be the one the programmer expected. Itis the beauty of Android’s design that the installed applications do not have to have beendesigned with knowledge of future extensions as long as developers adhere to some rulesoutlined in this paper.

In addition to Intents, Android ensures extensibility by allowing applications to share in-formation with other components through ContentProviders. By providing this functionalityit is ensured that information is accessible independently of the format used by the originalapplication. Developers need to get used to the fact that they are not accessing files ordatabases, but instead request information from another component, which hides the detailsof how the information is stored on disk. In terms of extensibility this allows components toaccess information without needing to know the technical intricacies involved.

6.2 A mobile operating system

Other mobile platforms’ development paradigms usually orient themselves after existingdesktop platforms. This is understandable of the players, who had already developed adesktop platform (Apple, inc., Microsoft, inc.), but also those who only distribute mobileplatforms (like Symbian foundation, previously Nokia, previously Symbian Ltd.) use a tra-ditional approach. The idea presumably being to ease the learning curve for new developers.In so far as they succeeded the special requirements placed upon developers by a mobileplatform voided some of that advantage.

31

6 Evaluation

Android takes a different approach. It breaks with traditional development approachesinstead opting to support a model better suited to mobile platforms. The core system isfundamentally aware of resource limitations and puts some burden on the developer to makehis application work well in resource constrained environments. The upside of this approachis that to make an application work well in the mobile environment developers do not needto deal with low-level issues specific to mobile devices.

Most components of an Android application get support for the mobile domain for free.They are separate from other parts of the application and defined in such a way that theyonly need to respond to events. They are inactive for most of the time, not requiring manyresources. Android Activities, which – as the reader will certainly recall – are user facingcomponents of an application, must be able to cope with more complex interactions.

While Android will for the most part handle changes in the environment behind the scenes,Activities need to adhere to a special life-cycle, which allows Android to call a function onthe Activity when something changes, like it loosing focus or resources running low.

Other issues of mobile devices are loss of network connection or positioning signal. Theseare taken care of for the user, because Android abstracts access to the hardware, instead re-quiring the user to request connections to backend systems, which handle unforeseen changesin the environment.

6.3 Proven technology

User interfaces and other common functionality are handled in Android in much the sameway it is handled on desktop operating systems. Android does not reinvent the wheel,instead adopting proven techniques. Some of this functionality is taken as is (e.g. the sqlitedatabase) or modeled after existing approaches (GUI creation through XML definitions).In other places proven interfaces are re-used (like the location API, which Android copiedpretty much verbatim from JSR-179).

In addition Android ships with functionality traditionally provided through third partysoftware, such as databases. Some non-traditional components (some of which have beendeveloped by opensource projects) shipped with Android include sqlite, openGL, Googlemaps (which is an optional API, not guaranteed to be available on every Android system),GTalk (now dropped) and the location system.

6.4 Developers

Android applications are written in Java, which makes them easy to understand by new-comers. Information not normally required to run a Java application - like which IntentsIntentReceivers can handle - is collected in the Manifest.xml file. Creating user interfaces isquite intuitive thanks to the XML based description format. Responding to Intents shouldbe familiar to anyone with experience using Java.

The more alien parts of Android are also easy to understand. Applications using data notsupplied by the OS can create a ContentProvider. If the application has a user interfaceit requires a View. To respond to an Intent it uses IntentReceivers. To cause other appli-cations to react to itself, the application can broadcast an Intent. Interoperation betweencomponents and applications is made easy and built into the very heart of the system.

32

6.5 State of the Android

The way applications are composed of several small pieces of software working in concerttakes getting used to. Developers need to understand what to use Intents for and how theyconnect pieces of the application. An application is made up of many discreet pieces, sharingof information is built into the system and is much simpler than comparable approaches likeaccessing the same database. This affords the developer the ability of having an existingapplication do large parts of the current activity for him.

Developers wanting to work on Android applications face a learning curve at first. Howeverthe system is designed in such a way as to make it seem natural after this learning curve hasbeen overcome.

The most obvious difference to other mobile platform and traditional application develop-ment is how applications are split into several components. Each component handling onlya very small part of the whole application. Some developers may be faced with an urge tobuild applications in a way they are familiar with. Given that each type of component isrestricted in the features available to it (consider – for example – the fact that Activities aresuspended when the user switches to a different Activity), this approach is bound to fail.When developing this project the author has decided to go through several re-factorings ofthe project until he was satisfied that the design did not place any unnatural restrictions onthe application. It turned out that the most fitting designed made as much use of Android’sbuilt-in capabilities as possible.

6.5 State of the Android

As expected Android was not perfect at the time this project was conducted. While at theend of the project the final stages of Android’s 1.0 release were put in place, the project wasdeveloped using Android release m5, which was current at the time the project started. Thisevaluation concentrates on this version. All statements about Android’s current capabilitiesand short-comings are in light of the early state of the platform and may (and probably will)have changed since. It is expected that many bugs mentioned here have been fixed.

That being said, Android had a number of annoying flaws. The early look SDK containedmany buggy components, which made the task of telling bugs in the program from systembugs quite hard and time consuming. This made for an unpleasant development process asany malfunctioning component had to be debugged as if the error had been made in theapplication, not the system libraries. Once the official Android bug tracker had been madeavailable, this became easier, but remained a drain on the developer’s motivation.

Relatedly, missing functionality, which was not clearly marked as such, was frequentlyassumed to be a mistake in the use of the functionality. For example, inter-component pass-ing of exceptions was unimplemented in the versions used during the project. Android –being based upon the interaction of many small components – involves a large amount ofcooperation between components. The combination of these made many problems, whichcould have been easily spotted in a monolithic application, exceptionally hard to find. Com-ponents seeming to have frozen or taken an unexpected control path frequently turned outto be functioning as expected. Android logs these exceptions to a debug log. Having discov-ered this made the development process easier, but still required the intuition that missingfunctionality could have been caused by exceptions in a different component.

33

6 Evaluation

6.6 Extensibility of the GeoBoxing application

The GeoBoxing system is built to respect Android’s conventions as much as possible. Assuch it provides a number of ContentProviders and uses implicit Intents to start Activitieswhere ever it does not conflict with the user interaction to do so. Thus replacing GeoBoxingcomponents should be as easy as specifying that the application can handle one or more ofthe same intents as GeoBoxing and acting upon it.

For developers seeking to build upon the current version of GeoBoxing and extend its codethe application has been written with extensibility in mind. Concepts which are realized inparticularly unfamiliar ways in Android have been documented with special emphasis.

6.7 Lessons learned

Android’s development model is different from that in use on other mobile platforms orthe desktop. This makes developing mobile applications easier on the one hand, but makeslearning the new platform harder. While the changes seem quite obvious the proper mindsetto make the application’s components work well together proved quite hard to acquire.

This bigger picture is not very well presented in Android’s documentation. The technicaldetails are well documented, but the user is left to his own devices to get a feeling for appli-cation development on Android. It is the author’s hope that this paper and the applicationsupplied with it will ease this step for many developers.

34

7 Summary and Conclusion

This project evaluated the Open Handset Alliance’s Android platform by developing alocation-based-service project utilizing many of Android’s unique features. The versionunder evaluation was m5-rc14, which was the current version during most of the project.

As was expected of a pre-release SDK first impressions were not flawless. However thegeneral mode of application development on Android was appreciatively suited to modernmobile devices. With Android a new application programming paradigm previously unuti-lized in the dominant mobile platform was introduced. It minimizes the responsibility ofmobile applications to respect the unique circumstances posed by mobile devices.

In addition to being developed especially for mobile devices, the Android platform isuniquely extensible through Intents and ContentProviders. Intents make late runtime bind-ing between applications possible, ContentProvider ease sharing of data between and withinapplications. These features allow pieces of applications or complete applications anywhereon an Android device to be replaced or superseded by newly installed ones.

Location-based services are not an afterthought in Android. The core Android systemships with a location API similar to JSR-179 and one of the earliest optional APIs addedby Google was a Google Maps widget. Unfortunately in versions following m5 Androidlost support for built-in peer-to-peer communication, which would have enabled or easeddevelopment of cooperative location-based applications. For this project it meant that theproject would not be testable on real devices in the foreseeable future. Fortunately theemulator provided in the SDK allowed a decent evaluation of the application.

Android provides new functionality for the development of location-based services. Itallows rapid development of new functionality by re-using existing applications. The de-velopment paradigm requires learning effort by new developers, but this pays off throughsimplified application development, especially through the ability to offload many responsi-bilities to the operating system. The burden on developers when adapting a design to mobiledevices are kept to a minimum.

35

7 Summary and Conclusion

36

List of Figures

5.1 FriendListActivity showing possible actions on a friend . . . . . . . . . . . . . 225.2 SendMessageActivity ready to send . . . . . . . . . . . . . . . . . . . . . . . . 235.3 ViewLocationActivity showing the position of a friend. (Map data not shown

due to missing support for Google Maps API keys in Android m5.) . . . . . . 245.4 Activity lifecycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

37

List of Figures

38

Bibliography

[AM08] Curro Dominguez Angel Machin. Integrating mobile services and content with theinternet. In Proceedings of the 17th International World Wide Web Conference(WWW2008), 2008.

[Bry04] Rod Bryant. Lessons learnt in assisted gps. In 2004 International Symposium onGNSS/GPS, 2004.

[DJ04] J. Arkko D. Johnson, C. Perkins. Mobility support in ipv6, 2004.

[Goo08a] Inc. Google. Accessing Content Providers, January 2008. [Online].

[Goo08b] Inc. Google. Anatomy of an Android Application, January 2008. [Online].

[Goo08c] Inc. Google. Android Application Design Philosophy, January 2008. [Online].

[Goo08d] Inc. Google. Android SDK M5 Release - API changes Overview, June 2008.[Online].

[Goo08e] Inc. Google. android.app.Activity, January 2008. [Online].

[Goo08f] Inc. Google. android.app.Activity, June 2008. [Online].

[Goo08g] Inc. Google. android.app.Notification, January 2008. [Online].

[Goo08h] Inc. Google. android.app.NotificationManager, January 2008. [Online].

[Goo08i] Inc. Google. android.content.ContentProvider, January 2008. [Online].

[Goo08j] Inc. Google. android.content.Intent, January 2008. [Online].

[Goo08k] Inc. Google. android.content.IntentReceiver, January 2008. [Online].

[Goo08l] Inc. Google. android.location.GeoCoder, June 2008. [Online].

[Goo08m] Inc. Google. android.location.Location, Jun 2008. [Online].

[Goo08n] Inc. Google. android.location.LocationManager, Jun 2008. [Online].

[Goo08o] Inc. Google. android.location.LocationProvider, Jun 2008. [Online].

[Goo08p] Inc. Google. android.view.View, January 2008. [Online].

[Goo08q] Inc. Google. com.google.android.maps.MapView, Jun 2008. [Online].

[Goo08r] Inc. Google. Google APIs and Services, Jun 2008. [Online].

[Goo08s] Inc. Google. Location-based Service APIs, January 2008. [Online].

39

Bibliography

[Goo08t] Inc. Google. Security and Permissions in Android, January 2008. [Online].

[Gro06] JSR 179 Expert Group. Location API for Java(tm) 2 Micro Edition, February2006.

[JH07] Peter Saint-Andre Joe Hildebrand. Xep-0138: Stream compression, September2007.

[Ltd07] Symbian Software Ltd. Symbian Location Acquisition API, 2007.

[Mor08] Dan Morrill. Accessing content providers, August 2008. [Online].

[Net08] Symbian Developer Network. Introduction to Location-based Services on SymbianOS, February 2008.

[Rub07] Andy Rubin. Where’s my gphone?, November 2007. [Online; accessed 5-November-2007].

[Wik08] Wikipedia. Mobile blogging — wikipedia, the free encyclopedia, 2008. [Online;accessed 15-May-2008].

40