Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Facoltà di Ingegneria Corso di Studi in Ingegneria Informatica tesi di laurea Service Discovery with the Google Android mobile platform Anno Accademico 2007/2008 relatore Ch.mo prof. Stefano Russo correlatore Ing. Marcello Cinque candidato Marco Faiella 885/139 I To my grandmother. I hope you’re proud of me. II Ringraziamenti Non inizierò questa pagina dicendo che è la più difficile da scrivere… vabbè, l’ho detto! Prima di tutto ringrazio i miei genitori per il loro supporto morale ed economico nei miei anni di studi all’università. Sapete che non sono molto bravo con le parole e per questo ho sempre preferito dimostrarvi il mio affetto con le azioni, ma è abbastanza difficile esprimere questo in una tesi di laurea, a meno che non consideriate la tesi stessa un mio atto di amore per voi. Grazie al Prof. Stefano Russo ed all’Ing. Marcello Cinque per la loro guida ed il loro supporto durante lo sviluppo di questo progetto. Inoltre, grazie al Prof. Duncan Smeed, per averci dato l’idea di un lavoro sulla piattaforma Android e per la sua gentilezza ed il suo aiuto nelle fasi iniziali di questo progetto, durante la nostra permanenza a Glasgow. Dato che non ho scritto una pagina di ringraziamenti per la tesi della triennale, approfitto di questa per ringraziare anche la mia prima relatrice, la Prof.ssa Anna Rita Fasolino, ed il mio primo correlatore, l’Ing. Porfirio Tramontana. Vi ringrazio per avermi guidato nel tirocinio e nella tesi triennale e per avermi sopportato, perché in effetti sono stato un bel rompiscatole. Grazie ai miei amici, primo fra tutti Marco Ortolani, con il quale ho vissuto a Glasgow durante l’Erasmus e con il quale ho lavorato a questa tesi di laurea. Grazie anche ad Emilio, Terry, Debora, Marco, Stefania, Luca, Enzo, Antonella, Virginia e tutti quelli che ho III dimenticato di menzionare. Grazie anche ai miei compagni di Taekwon-do ed amici Francesco e Cosimo. Per rimanere in ambito sportivo, ringrazio il Taekwon-do: un’arte marziale che mi ha permesso di stringere amicizie (con un pizzico di rivalità) in tutta Italia, nonché all’estero, e che si è rivelata un’essenziale valvola di sfogo nei momenti più difficili. Si può dire che la mia carriera nel Taekwon-do abbia seguito di pari passo quella accademica, poiché ho iniziato a praticarlo al mio primo anno di università ed ho conseguito la cintura nera in concomitanza con la mia laurea specialistica. Grazie anche a tutti i miei parenti: zii, zie, cugini, cugina (ne ho una sola)… grazie a tutti voi! Concludo con un ringraziamento al mio amore: la mia ragazza, Laura, che mi è stata vicina, anche se lontana da casa mia, in interminabili sessioni di Skype. Grazie per il tuo supporto nei momenti di difficoltà e per la tua tolleranza delle mie freddure. Ti amo più di quanto io possa mai scrivere in questa semplice pagina! IV Acknowledgements I will not begin this page by saying that this is the hardest page to write… whoops! I said it! First of all I would like to thank my parents for the moral and economical support in my years of study at the university. You know, I’m not so good with words, so I always preferred to show you my love with my actions, but it is quite difficult to convey this in a thesis, unless you don’t consider the thesis itself as an act of love for you. Thanks to prof. Stefano Russo and eng. Marcello Cinque for their guidance and support during the development of this project. Moreover, thanks to prof. Duncan Smeed, for giving us the idea of a work based on the Android platform and for his kindness and help in the first phases of the development of this project, during our staying in Glasgow. Since I didn’t write an acknowledegments page for my bachelor degree, I well out of this one to thank my first supervisor, Prof. Anna Rita Fasolino, and my first co-supervisor, Eng. Porfirio Tramontana. Thank you for having guided me during my apprenticeship and my first degree project, and for having tolerated me: I must admit I have been a pain. Thanks to my friends, first of all Marco Ortolani, with whom I lived in Glasgow during my Erasmus and worked on this graduation project. Thanks also to Emilio, Terry, Debora, Marco, Stefania, Luca, Enzo, Antonella, Virginia and everyone else I forgot to mention, and thanks to my Taekwon-do mates and friends Francesco and Cosimo. V As for the sport, I must say thank you to the Taekwon-do, a martial art which allowed me to conclude friendships (with a wee bit of competition) in Italy and foreign, and which has been a relief valve in the hardest moments. I can say that my career in the Taekwon-do has followed hand in hand my academic career, since I began to practice it in my first year at the university and achieved the black belt concomitantly with my master degree. Moreover, thanks to my relatives: uncles, aunts, cousins… thanks to everyone! I conclude this page by saying thank you to my love: my girlfriend Laura, for staying by my side, even if far from my home, in endless Skype sessions. Thanks for your support in the moments of difficulty and for your tolerance of my jokes. I love you more than I can say in this simple page! VI VII Service Discovery with the Google Android mobile platform Index Introduction .......................................................................................................................... 10 Chapter 1: The Service Discovery ........................................................................................ 13 1.1 Overview on the Service Discovery ....................................................................... 14 1.1.1 Elements of the Service Discovery..................................................................... 14 1.2 Requirements for the service discovery ................................................................. 16 1.3 Some solutions for service discovery ..................................................................... 17 1.3.1 Jini ...................................................................................................................... 17 1.3.2 Bluetooth ............................................................................................................ 19 1.3.3 Esperanto ............................................................................................................ 21 Chapter 2: Overview of the Core Framework ...................................................................... 23 2.1 Framework Architecture ........................................................................................ 24 2.2 Framework description........................................................................................... 25 Chapter 3: The Google Android Mobile Platform................................................................ 30 3.1 Android Architecture.............................................................................................. 30 3.2 The Dalvik Virtual Machine .................................................................................. 32 3.3 Lifecycle of an Android Application ..................................................................... 32 3.4 Anatomy of an Android application ....................................................................... 34 3.4.1 Activity ............................................................................................................... 35 Intent and Intent Filter ........................................................................................ 36 3.4.2 3.4.3 Intent Receiver.................................................................................................... 37 3.4.4 Service ................................................................................................................ 37 3.4.5 Content Provider ................................................................................................. 38 3.5 Android User Interface ........................................................................................... 38 3.5.1 Hierarchy of Screen Elements ............................................................................ 39 3.5.2 Views .................................................................................................................. 39 3.5.3 ViewGroups ........................................................................................................ 39 3.5.4 A Tree-Structured UI .......................................................................................... 40 3.6 The Android Manifest ............................................................................................ 41 3.7 Resources and the R.java file ................................................................................. 41 3.8 Developing an Android application ....................................................................... 42 3.9 Security model........................................................................................................ 45 3.10 Android and the Service Discovery .................................................................... 46 8 Service Discovery with the Google Android mobile platform Chapter 4: Development of an Android-based Service Discovery application .................... 47 4.1 Technical Requirements ......................................................................................... 47 4.2 Design of the services Repository .......................................................................... 47 4.3 Design of the Discovery Service ............................................................................ 49 4.4 Implementation of the Discovery Service .............................................................. 51 4.4.1 Server Side.......................................................................................................... 52 4.4.2 Client Side .......................................................................................................... 54 4.5 Interactions ............................................................................................................. 59 Chapter 5: Examples of use .................................................................................................. 63 5.1 The Main screen ..................................................................................................... 64 5.2 Scenario 1: Selection of a not installed service ...................................................... 64 5.3 Scenario 2: Selection of an updatable service ........................................................ 67 5.4 Scenario 3: Selection of an already installed service ............................................. 69 Conclusions .......................................................................................................................... 72 Future Works ........................................................................................................................ 74 Appendix A: How to install the Android environment on Eclipse ...................................... 75 Appendix B: Creating a first simple Android application .................................................... 77 Appendix C: Creating an application with a complex UI .................................................... 82 References ............................................................................................................................ 89 9 Service Discovery with the Google Android mobile platform Introduction The technological progresses in the last years have made the users able to dispose of a large amount of mobile devices. In the first years, between these devices, there was a great diversification: some examples are mobile phones, media players, PDAs, laptops, etc.. However, the trend in the last years has been the integration of all these functionalities in a single mobile device. Great effort has been made by the producers to obtain the smallest device integrated with the largest amount of functions. In this scenario, and with the spreading of the wireless connections, the traditional distributed systems are evolved in nomadic computing systems, characterized by a fixed network which can connect different mobile network devices. Thanks to their mobile devices, the users are able to interact with the environment, using the available services. Such idea may be adopted by public structures such as museums, libraries, universities, and so on. Due to the great diffusion of the mobile devices, many companies matured the idea of the implementation of mobile platforms oriented to the services providing. These architectures are often referred as Services Oriented Architectures (SOA) and they provide a new development paradigm for the distributed applications, which is well suited for such a dynamical environment. In a research project between CINI (Consorzio Interuniversitario Nazionale per l’Informatica) and the WiFi People company, called “WiFi People – CRONOS”, the design 10 Service Discovery with the Google Android mobile platform of a services framework, which would provide different services like VoIP, GPS positioning and Instant Messaging, has been conceived. This framework should provide a service discovery mechanism, which should allow the user to get a list of the available services on a central server, or on other mobile devices, and download and install the desired ones. In this work will be discussed the development of a service discovery application for this framework, based on the Google Android mobile platform. The idea of this work has born during the study of the Google Android mobile platform, performed at the University of Strathclyde, in Glasgow, with the colleague and friend Marco Ortolani, in agreement with the Università degli Studi di Napoli Federico II and with the professors Stefano Russo and Duncan Smeed. The reason of this choice is the high promise of the Google Android mobile platform. This platform has been announced in 2007 by Google Inc., with the partnership of the Open Handset Alliance, a consortium of several companies which includes HTC, eBay, Qualcomm, T-Mobile, Motorola, NVIDIA and many others. The goal was the development of an Open Source Linux-based software stack for mobile devices, which could rival with the well consolidated closed systems Windows Mobile and Symbian. The first Android device is the HTC G1, and it has been released in October 2008, with the 1.0 version of the Android SDK. From that date many other devices have been announced and will be released in 2009. In the first chapter of this work we will discuss the basic characteristics of the service discovery, with some example of the most common solutions. The second chapter will show the services framework developed in the “WiFi People – CRONOS” project, its structure and how it works. In the third chapter we will make an overview on the Google Android mobile platform, with a special attention to the architecture and the applications lifecycle. In the fourth chapter we will discuss the design and implementation of the discovery service and a client application for Google Android. 11 Service Discovery with the Google Android mobile platform Finally the fifth chapter will show some use examples of the developed application. 12 Service Discovery with the Google Android mobile platform Chapter 1 The Service Discovery In the last years there has been an exponential spreading and evolution of devices for mobile computing. This rapid diffusion has influenced the evolution of the distributed systems from a technological and a software engineering point of view. In particular, from a software engineering point of view, the classic models like the distributed objects, suitable for static environments in which each application has a well known space of names, are evolved as an answer to the necessity of a more dynamical scenario, in which the devices can continuously connect and disconnect from different network infrastructures and use the services (not necessarily know a priori) provided by each of them. From this idea has born the notion of Services Oriented Architectures (SOA). The applications developed with this approach are conceived as a collection of independent services, which show a well defined interface to the potential user. The SOA supports the application in the search of services, the selection and the combination of the needed ones, in order to obtain the desired functionalities. In these architecture a service discovery mechanism is needed for the search of unknown services: the services should be searched when needed and the search should be based on 13 Service Discovery with the Google Android mobile platform what the services offer, and not on their name. Moreover, the search must consider parameters like the compatibility with the device and the personalization. 1.1 Overview on the Service Discovery We can define service discovery as a collection of protocols and mechanisms which help the device or the software to know which services are available. Service discovery technologies are implemented in order to allow the user to find, configure and use the services in a network with the minimum effort provided by the user. The service discovery ends when all the needed services have been found. After this phase, we can define another one called service delivery, which includes the access mode to the service and its use [1]. 1.1.1 Elements of the Service Discovery In a discovery protocol we can identify four main entities [1]: • Service: a logic entity defined by a public interface or a descriptor. • Client Agent: the services search software (also called service requestor). • Service Agent: the software component implementing the Service, coherently with its descriptor. It may act also as Client Agent if it needs other services to implement its one. • Registry: the place where the information about the services are stored. It answers to the request of publication or search of services. Usually the registry has an entry for each service provided by the Service Agent and the entries may be structured in different ways, such as trees, graphs or relational databases. Moreover, the registry may be 14 Service Discovery with the Google Android mobile platform implemented locally (on the devices providing the services) or remotely and, in this last case, it may be centralized or distributed. In order to let know the existence of a service, the Service Agent must make public its availability, using a discovery advertisement mechanism. A Client Agent uses a service discovery mechanism to search for a service in the environment. First of all it must find the Registry (or the single Service Provider) to send a query to, then it must send the query and obtain the result. The query consists in a record called Service Description Record (SDR) and the result of this query is obtained by the matching between the SDR with the ones stored in the Registry or in the local repository. The search may be performed in different ways: • For a specific service • By class of services • By browsing the available service in the repository However, it is important to respect the principle of boundary: the division of the world in environment with well defined bounds. In this way the service discovery requests may be explicitly performed inside or outside the boundary. This principle is important because, due to their nomadic nature, the devices may find services that are physically far away from their current location, making them unable to use the services themselves (for example a print service) [1]. Figure 1.1 synthesizes the main elements of the service discovery. 15 Service Discovery with the Google Android mobile platform Figure 1.1 – The main elements of the service discovery 1.2 Requirements for the service discovery The functional requirements for the service discovery in a nomadic computing environment are [1]: • Mobility support: the discovery mechanisms must allow the device to find services independently from its position and state (connected or not to the core infrastructure of the nomadic computing). • Dynamicity support: since the connection may not be dependable, during the service discovery only the actually available services must be discovered. Moreover the discovery infrastructure must be context-aware, due to the high dynamicity of the execution context in this scenario. • Completeness of the search mechanism: the discovery protocol must make available a complete set of search modes (as described in the previous paragraph). • Bounds definition: the boundary allows the client to reduce the search area, with a performance improvement. Moreover we can define a set of non-functional requirements for a discovery 16 Service Discovery with the Google Android mobile platform infrastructure [1]: • Scalability: the discovery must not introduce an overhead with the increasing of the system’s size. • Lightness: in a nomadic computing environment there may be devices with poor elaboration abilities, so the support software must not heavily charge the CPU and the memory of the mobile devices. • Heterogeneity: due to the differences between the mobile devices, the discovery protocol must define an as general as possible description format for the services. • Reliability: a malfunction in the discovery infrastructure may harm the next discovery process, so it is important to make this infrastructure dependable. • Safety: malicious users should not access to “safe” services. 1.3 Some solutions for service discovery In this paragraph we will make an overview of the most common solutions for the service discovery. 1.3.1 Jini Jini is a service discovery and advertisement systems based on the Java Virtual Machine, and this is an advantage in terms of code mobility and platform independence. Jini implements a reliable connection-oriented communication mechanism, with multicast support. 17 Service Discovery with the Google Android mobile platform Figure 1.2 – Jini main entities As shown in Figure 1.2, the Jini main entities are coherent with the definition previously given of the main entities in the discovery service. In fact we can find: • Services • Lookup services • Clients And the services themselves may act as clients if needed. The Jini service discovery request and registration work as follows [7]: • In order to register or request a service, the service or the client must first of all find a Lookup service (service discovery) with a multicast request protocol. • After the Lookup service has been found, the service/client communicates with it using an unicast discovery protocol. • The Lookup service sends to the requester an instance of a class called service registrar, which allows the remote control of the Lookup 18 Service Discovery with the Google Android mobile platform service. • At this point the service is able to register itself on the Lookup service using the join method and the client is able to search for a service using the lookup method. With the lookup method, Jini clients send a service template as a parameter. By this service template, the client may search for a service by attribute, by interface or by ID. The result of the request is an instance of the service matches class, which contains an array of the service objects corresponding to the search parameters. There is also a notify method, which informs a client on the registration of a new service, or on the update or deletion of an existing one. 1.3.2 Bluetooth The Bluetooth protocol stack includes SDP (Service Discovery Protocol), a service discovery protocol for the localization of the available services in a Bluetooth piconet [8]. The SDP’s APIs provide the following operations: • Service search by class • Search for a specific service (by ID) • Services browsing • Piconet devices discovery 19 Service Discovery with the Google Android mobile platform Figure 1.3 – The SDP protocol Figure 1.3 shows the behavior of the SDP protocol. A client application searches for services sending an SDP request through a SDP client to a SDP server. The SDP server implements a service records list. Each record describes the characteristics of the services provided by the Server Application. The communication between SDP client and server works with the request/response model. The SDP client may perform the following operations: • ServiceBrowse(): for the services browsing in the neighbor devices. • ServiceSearch(): for the research of a specific list of services in the neighbor devices. • EnumerateRemDev(): enumerates the remote devices in the neighborhood. As a transport service, SDP uses the L2CAP (Logical Link Control and Adaptation Protocol) connection oriented protocol. 20 Service Discovery with the Google Android mobile platform 1.3.3 Esperanto Esperanto is a middleware services oriented architecture for nomadic computing environments, developed by the Università degli Studi di Napoli Federico II [1]. It represents a complete service discovery and service delivery platform. The goal of Esperanto is an integration of the existing discovery and delivery technologies, in order to solve the interoperability problems between different architectures. We will define domain a set of devices implementing a discovery and delivery technology (Jini, Bluetooth, UPnP). A nomadic environment may contain one or more Esperanto domains and one or more different domains, called generic domains, as shown in Figure 1.4 Figure 1.4 – A nomadic computing environment with different domains For example, the X and Y domains may be Esperanto domains and the W and Z domains may be respectively a Jini and an UPnP domain. The Esperanto architecture allows a transparent communication and interaction between different discovery and delivery technologies, in respect of the requirements of a nomadic computing environment. 21 Service Discovery with the Google Android mobile platform The architecture is shown in Figure 1.5: Figure 1.5 – The Esperanto architecture In Figure 1.5 it is possible to identify Esperanto domains and generic domains. These domains are connected using domain specific agents (or Esperanto agents for Esperanto domains) and mediators. The domain specific agent is charged of the integration of the discovery and delivery protocols. The mediators are implemented for service delivery functions, in order to allow to the clients a transparent communication with different servers. An application dialogues only with a mediator, which forwards the requests to the domain specific agent. The communication between different domains, located in different network infrastructures, is performed using brokers (middlewares, sockets, etc.). 22 Service Discovery with the Google Android mobile platform Chapter 2 Overview of the Core Framework In the research project between CINI (Consorzio Interuniversitario Nazionale per l’Informatica) and the “WiFi People” company, called “WiFi People – CRONOS”, a framework has been created with the following characteristics [3]: • An Ad-hoc system, independent from any fixed infrastructure. In order to achieve this, the framework is completely (or almost completely) resident on the mobile device. • From a user’s point of view, the primary service provided by the framework is the automatic configuration and distribution. A new device linked to the network is able to discover and download from the nearest mobile device the applications which use the framework’s services. The framework automatically charges itself of the distribution of the services needed by the applications. • From a programmer’s point of view, the framework respects the middleware’s characteristics of transparency, allowing the programmers to be able to easily create services-based applications. Moreover the framework offers an easy maintenance, since it makes the programmer able to change the client application or the component itself, without changing any application which uses it. 23 Service Discovery with the Google Android mobile platform In this chapter, first the architecture of the Framework will be analyzed then a brief description of its underlying function: how it has been done and how to communicate with it. Then an overview of the VoIP technology will be composed in order to have an encompassing and clear vision about the entire environment we are going to work for and of the Voice over IP technology. 2.1 Framework Architecture The framework is composed of a group of elements and each element implements a service. The components are independent, in this way the user will be able to chose only the services he needs. Figure 2.1 – Framework’s overall architecture The purple elements in Figure 2.1 are the management functions of the framework. The green elements are the services, such as Instant Messaging, VoIP, etc.. These 24 Service Discovery with the Google Android mobile platform services are available to the programmer, providing the APIs needed for the development of a new application or the integration of the service with an existing application. Otherwise, they may be directly used, in order to have the execution of the service, such as it is implemented in the Framework. Moreover, each service has a single implementation in a defined language (i.e. Java), then the “Core Framework” will make it available to every application, regardless of the platform and the programming language. This solution makes the framework’s maintenance quite easy, since the maintenance operations on a service are made just on a single implementation of it. A client application, implemented in any programming language (blue elements), may easily access the services, since the framework acts as a middleware. 2.2 Framework description The Framework is mainly composed of two parts: a part composed of the services and the other one with which the user applications interact. The Framework has been developed following the Proxy Pattern. In the picture it is possible to notice the different levels [3]. 25 Service Discovery with the Google Android mobile platform Figure 2.2 – The Framework architecture We will now discuss the Core level because the whole communication between the application level and the service level is encapsulated within it, and so it is trough this level that an application can access to the Framework components. It is divided into two parts: the client side and the server side. Each part has its own entity: the Connector (client side) and the Acceptor (server side). The first resolves the service while the second checks if the service requested exists. If so, it will pass the reference to the Connector. Since the communication is socket-driven, the reference could be a local port on which will run the requested component. In other words, when a client requests a service, the communication is divided in three main phases: • The Connector is activated and sends the request to the Acceptor. • The Acceptor process the request. • The Connector receives an answer from the Acceptor. The communication between Connector and Acceptor starts using an hanshake. 26 Service Discovery with the Google Android mobile platform In the following picture is shown the java interface class diagram implemented from the acceptor: Figure 2.3 – Acceptor Interface This first step of the communication is made using the method ResolveService(). In fact, when this method is invoked, it compares the argument with each of the available services – which are coded in the interface – and allocates the requested service in order to obtain the the port if it is present otherwise rises the exception “Service NoTFoundExcpetion”. Once completed, the Acceptor will have to implement the interface and the method of resolution and activation of the available services. The framework’s protocol evolves in a defined sequence of phases: • The client side creates a Stub for the desired service. • The Stub asks the Connector to resolve the port of the Core component (if available). • The Connector calls the Acceptor on a defined port (i.e. 3000). • The Acceptor receives the request and checks the availability of the chosen service. If the service is available but not active, the Acceptor activates it and sends the port number to the Connector. Otherwise, if the service is active, the Acceptor just sends the port number to the Connector. Finally, if the service is 27 Service Discovery with the Google Android mobile platform not available, the Acceptor sends a “service not available” exception. • The Connector receives the response and, if it is positive, sends back to the Stub the port number for the requested service. Otherwise the connector sends an exception to the Stub. • The Stub connects to the received port and starts a communication with the service’s Skeleton. From this point the Stub will communicate directly with the service, without the Connector’s mediation. Once the connection between Stub and Skeleton has been established, the Stub can forward the requests to the Skeleton as follows: • The Stub receives a request from the client application to call the f(x) method. • The Stub marshals the parameter and sends the request to the Skeleton through the pair (code, parameters[]). • The Skeleton receives the request and unmarshals the code and the parameters. Then it forwards to the service the request to call the selected method (through an up-call). After the completion of the operation, the service has to send back the results. This is made through a remote call-back mechanism: • The service catches an event to send back and codes it in a pair (code, value), where the code is defined in the Stub’s and Skeleton’s interfaces and the value (optional) is a completion of the result. Then the service calls a notification method on the Skeleton, using the pair as a parameter. • The Skeleton receives the notification and forwards it to the Stub. • The Stub receives the notification and forwards it to the client application through a notification method. 28 Service Discovery with the Google Android mobile platform • The client application receives the notification and informs the user with a message. Through this mechanism it is possible to implement each Core service, since it makes easy to manage both the synchronous and the asynchronous communication. 29 Service Discovery with the Google Android mobile platform Chapter 3 The Google Android mobile platform 3.1 Android Architecture Android is a software stack for mobile devices that includes an operating system, middleware and key applications [4]. Figure 3.1 – The Android stack 30 Service Discovery with the Google Android mobile platform In Figure 1.1 is shown the overall architecture. It is composed of four layers: • Applications • Application Framework • Libraries (which includes Android Runtime) • Linux Kernel The whole architecture lays on a Linux 2.6 kernel. The Linux kernel is used as a hardware abstraction layer and it provides a proven driven model and a lot of existing drivers, security models, memory management, etc. The advantage of this solution is that every mobile device which can run Linux, can virtually run Android. The next level up includes the libraries. The libraries are all written in C/C++ and are used by the various components of the Android system. They are called by the developers through the Java interfaces. Next to the Libraries layer there is the Android Runtime, which is based on the Dalvik Virtual Machine. The Android runtime was designed for mobile devices with limited memory and limited CPU. The Android runtime includes also the Core Libraries, written in Java programming language, which contains the collection of classes, utilities, I/O, etc. Moving up again, there is the Application Framework, all written in Java programming language, and it is the toolkit used by all the applications. The most important component of the Application Framework is the Activity Manager, which manage the lifecycle of the applications and a common “back-stack” for user navigation. The upper level is the Applications layer. It includes a set of core applications, shipped with the base system and written using the Java programming language, such as an SMS program, a calendar, a browser, a contact list manager and others. 31 Service Discovery with the Google Android mobile platform 3.2 The Dalvik Virtual Machine The Dalvik virtual machine is a register-based virtual machine, unlike Java Virtual Machine, that is a stack based virtual machine, designed and written by Dan Bornstein with contributions from other Google engineers as part of the Android mobile phone platform. It is optimized for low memory requirements, and is designed to allow multiple VM instances to run at once, relying on the underlying operating system for process isolation, memory management and threading support. Dalvik is often referred to as a Java Virtual Machine, but this is not strictly accurate, as the bytecode on which it operates is not Java bytecode. Instead, a tool named dx, included in the Android SDK, transforms the Java Class files of Java classes compiled by a regular Java compiler into another class file format (the .dex format). Like the Java virtual machine (JVM) or the .NET/Mono virtual machine, Dalvik is a runtime environment that can serve as a platform for web applications, desktop applications, and (the emphasis in this case) mobile phone applications. Dalvik essentially compiles and runs java code in its own virtual machine, apparently, and uses the open source Apache Harmony class library (a clone of the standard classpath - java class libraries). Although JDK is open source, J2ME is not. This is why, rather than require phone makers to license JME as part of Android, Google built its own virtual machine [5]. 3.3 Lifecycle of an Android Application In Android, every application runs in its own process, which gives better performance in security, protected memory and other benefits. Therefore, Android is responsible to run and shut down correctly these processes when it is needed. Let’s assume the possible scenario: A user talks to his friend via mobile phone and he is asked to 32 Service Discovery with the Google Android mobile platform browse the internet (a talk is hold for a moment), find a picture of him in his Picasa Album, send it via Email back to his friend and resume a talk. Figure 3.2 In this situation, there are 4 different applications and 4 different processes running, but from the user point of view none of them are important, as Android manages CPU work and memory usage by itself. It means the user can travel through the applications forward and backward without thinking about how much memory is left or which processes are running at the time. First, as the user is talking to his friend, a specific Talk application is opened, which contains the activity manager. Before going to Web Browser application, the system saves a Talk state in order to remember that process. At this point, as a user holds a talk and opens a web browser, the system creates a new process and new web browser activity is launched in it. Again, the state of the last activity is saved. After that, the user browses the internet, finds his picture in Picasa album and saves it to particular folder. He does not close a web browser, instead he opens a folder to find saved picture. At this point, the user finds his saved picture in the folder and he creates a request to open an Email application. The last state is saved. Now assume that the mobile phone is out of the memory and there is no room to create a new process for Email application. Therefore, Android looks to kill a process. It cannot destroy Folder process, as it was used previously and could be reused again, so it kills Web Browser process as it is not useful anymore and locates a new Email process instead: 33 Service Discovery with the Google Android mobile platform Figure 3.3 The user opens Email application and sends a picture to his friend via email. Now he wants to go back to the Talk application and to resume a talk to his friend. Because of the previously saved states, this work is done fast and easily. Next, the user goes back to Web Browser application. Unfortunately, web browser process was killed previously so the system has to kill another process (in our case it is Email application process, which is not used anymore) in order to locate Web Browser process and manage the stack memory. Now the user comes back to the Talk application and resumes his talk with his friend. This example shows that it does not matter how many applications and processes are active or how much available memory is left, Android it manages fast and without a user interaction [5]. 3.4 Anatomy of an Android application The possible components of an Android application are: 34 Service Discovery with the Google Android mobile platform Activity Intent Receiver Service Content Provider UI component, typically corresponding to a single screen of the application. An application may be composed of more screens. In this case each screen is implemented as an activity Wakes up a predefined action through the external event. For example, for the application like Email Inbox, the developer should have intent receiver and register his code through XML to wake up an alarm notification, when the user receives e-mail. A task, which is done in the background. It means that the user can start an application from the activity window and keep the service work, while browsing other applications. For instance, he can browse Google Maps application while holding a call or listening music while browsing other applications A component, which allows sharing some of the data with other processes and applications. It is the best way to communicate the applications between each other An application doesn’t need the all four components but it needs just a combination of these. The components used by the application are declared in the file AndroidManifest.xml. 3.4.1 Activity Activities are the most common of the four Android building blocks. An activity is usually a single screen in the application. Each activity is implemented as a single class that extends the Activity base class. Each class will display a user interface composed of Views and respond to events. Most applications consist of multiple screens. For example, a text messaging application might have one screen that shows a list of contacts to send messages to, a second screen to write the message to the chosen contact, and 35 Service Discovery with the Google Android mobile platform other screens to review old messages or change settings. Each of these screens would be implemented as an activity. Moving to another screen is accomplished by a starting a new activity. In some cases an Activity may return a value to the previous activity – for example an activity that lets the user pick a photo would return the chosen photo to the caller. When a new screen opens, the previous screen is paused and put onto a history stack. The user can navigate backward through previously opened screens in the history. Screens can also choose to be removed from the history stack when it would be inappropriate for them to remain. Android retains history stacks for each application launched from the home screen [6]. 3.4.2 Intent and Intent Filter Android uses a special class called Intent to move from screen to screen. Intent describe what an application wants done. The two most important parts of the intent data structure are the action and the data to act upon. Typical values for action are MAIN (the front door of the application), VIEW, PICK, EDIT, etc. The data is expressed as a Uniform Resource Indicator (URI). While an intent is effectively a request to do something, an intent filter is a description of what intents an activity is capable of handling. An activity that is able to display contact information for a person would publish an IntentFilter that said that it knows how to handle the action VIEW when applied to data representing a person. Activities publish their IntentFilters in the AndroidManifest.xml file. Navigating from screen to screen is accomplished by resolving intents. To navigate forward, an activity calls startActivity(myIntent). The system then looks at the intent filters for all installed applications and picks the activity whose intent filters best matches myIntent. The new activity is informed of the 36 Service Discovery with the Google Android mobile platform intent, which causes it to be launched. The process of resolving intents happens at run time when startActivity is called, which offers two key benefits [6]: • Activities can reuse functionality from other components simply by making a request in the form of an Intent. • Activities can be replaced at any time by a new Activity with an equivalent. 3.4.3 Intent Receiver An IntentReceiver is used when a developer wants code in his application to execute in reaction to an external event, for example, when the phone rings, or when the data network is available, or when it's midnight. Intent receivers do not display a UI, although they may display Notifications to alert the user if something interesting has happened. Intent receivers are also registered in AndroidManifest.xml, but it is also possible to register them from code using Context.registerReceiver(). The application does not have to be running for its intent receivers to be called; the system will start the application, if necessary, when an intent receiver is triggered. Applications can also send their own intent broadcasts to others with Context.broadcastIntent() [6]. 3.4.4 Service A Service is code that is long-lived and runs without a UI. A good example of this is a media player playing songs from a play list. In a media player application, there would probably be one or more activities that allow the user to choose songs and start playing them. However, the music playback itself should not be handled by an activity because the user will expect the music to 37 Service Discovery with the Google Android mobile platform keep playing even after navigating to a new screen. In this case, the media player activity could start a service using Context.startService() to run in the background to keep the music going. The system will then keep the music playback service running until it has finished. Note that it is possible to connect to a service (and start it if it's not already running) with the Context.bindService() method. When the application is connected to a service, it can communicate with it through an interface exposed by the service [6]. 3.4.5 Content Provider Applications can store their data in files, a SQLite database, preferences or any other mechanism that makes sense. A content provider, however, is useful if a developer wants his application's data to be shared with other applications. A content provider is a class that implements a standard set of methods to let other applications store and retrieve the type of data that is handled by that content provider [6]. 3.5 Android User Interface User Interfaces (UI) in Android can be built within two ways: • defining XML-Code • writing Java-Code. Defining the GUI structure in XML is highly preferable, because the UI should always be separated from the business-logic. Additionally adapting a program from one screen-resolution to another is a lot easier [4]. 38 Service Discovery with the Google Android mobile platform 3.5.1 Hierarchy of Screen Elements The basic functional unit of an Android application is the activity. An activity can do many things, but by itself it does not have a presence on the screen. The UI is made with views and viewgroups - basic units of user interface expression on the Android platform. 3.5.2 Views A view is an object extending the base class android.view.View. It's a data structure whose properties store the layout and content for a specific rectangular area of the screen. A View object handles measuring, its layout, drawing, focus changes, scrolling, and key/gestures for the screen area it represents. The View class serves as a base class for all widgets - a set of fully implemented subclasses that draw interactive screen elements. Widgets handle their own measuring and drawing, so you can use them to build your UI more quickly. 3.5.3 ViewGroups A viewgroup is an object of class android.view.Viewgroup. As its name indicates, a viewgroup is a special type of view object whose function is to contain and manage a subordinate set of views and other viewgroups, Viewgroups makes possible to add structure to the UI and build up complex screen elements that can be addressed as a single entity. The Viewgroup class serves as a base class for layouts - a set of fully implemented subclasses that provide common types of screen layout. The layouts gives a way to build a structure for a set of views. 39 Service Discovery with the Google Android mobile platform 3.5.4 A Tree-Structured UI On the Android platform, is possible to define an Activity's UI using a tree of view and viewgroup nodes, as shown in the diagram below. Figure 3.4 – Groups of views The tree can be as simple or complex as it is needed to make it, and it is possible to build it up using Android's set of predefined widgets and layouts or custom view types that can be created. To attach the tree to the screen for rendering, the Activity calls its setContentView() method and passes a reference to the root node object. Once the Android system has the reference to the root node object, it can work directly with the node to invalidate, measure, and draw the tree. When the Activity becomes active and receives focus, the system notifies it and requests the root node to measure and draw the tree. The root node then requests that its child nodes draw themselves - in turn, each viewgroup node in the tree is responsible for drawing its direct children. As mentioned previously, each view group has the responsibility of measuring its available space, laying out its children, and calling draw() on each child to let it render itself. The However, the parent object has the final decision on where how big each child can be. 40 Service Discovery with the Google Android mobile platform 3.6 The Android Manifest The AndroidManifest.xml is a required file for every Android application. It is located in the root folder of the application, and describes global values, including the application components (activities, services, etc) that the package exposes to the ‘outer world’, the kind of data each activitiy can handle, and how they can be launched. Besides declaring the application's Activities, Content Providers, Services, and Intent Receivers, it is also possible to specify permissions in AndroidManifest.xml. 3.7 Resources and the R.java file Resources are external files (non-code files) that are used by the code and compiled into the application at build time [4], [6]. Android supports a number of different kinds of resource files, including XML, PNG, and JPEG files. The XML files have very different formats depending on what they describe. Resources are externalized from source code, and XML files are compiled into a binary, fast loading format for efficiency reasons. Strings are compressed into a more efficient storage form. Using resources in code is just a matter of knowing the full resource ID and what type of object your resource has been compiled into. The syntax for referring to a resource is: • R.resource_type.resource_name • android.R.resource_type.resource_name Where resource_type is the R subclass that holds a specific type of resource. resource_name is the name attribute for resources defined in XML files, or the file name (without the extension) for resources defined by other file types. Each type of resource will be added to a specific R subclass, depending on the type of resource it 41 Service Discovery with the Google Android mobile platform is. Resources compiled by the application can be referred to without a package name (simply as R.resource_type.resource_name). Android contains a number of standard resources, such as screen styles and button backgrounds. A project's R.java is an auto-generated file indexing all the resources of the project. This class is a sort of short-hand way to refer to resources included in the project. This is particularly powerful with the code-completion features of IDEs like Eclipse because it lets quickly and interactively locate the specific reference you're looking for. Additionally the existence of the resource is granted at compile-time, if available in the R.java file. 3.8 Developing an Android application Basically an Android application is composed of two parts: the source, which contains the Java code of the application, and the resources, such as the XML file which describes the layout of the screen, icons, images, etc. A simple Android project contains a main Activity, which is an object representing a single screen of the application and is composed by one or more Views, and the resource files needed by the base application. The first pass is the design of the User Interface. The layout of a screen is described by an XML document. The next step is the implementation of the source code. The source code is composed of a class that extends the basic class Activity. This class implements different methods. Each method corresponds to an event: • onCreate: it is invoked when the activity is created and it is used for the initialization of the activity itself • onPause: it is invoked when the user leaves the activity without quitting it. It is useful to save the state informations of the activity in order to grant the 42 Service Discovery with the Google Android mobile platform persistence. • onDestroy: it is invoked before the destruction of the activity and it is useful to clean data and memory These are the most common methods but there are much more of them. In Figure 1.2 is described the life-cycle of an activity with the invocation of different methods [4]. Figure 3.5 – Life-cycle of an Android activity A developer should predefine and list all components, which he wants to use in the specific AndroidManifest.xml file. It is a required file for all the applications and is located in the root folder. It is possible to specify all global values for the package, all the components and its classes used, intent filters, which describe where and when the certain activity should start, permissions and instrumentation like security control and testing. Here is an example of AndroidManifest.xml file: 43 Service Discovery with the Google Android mobile platform <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=http://schemas.android.com/apk/res/android package="dk.mdev.android.hello"> <application android:icon="@drawable/icon"> <activity class=".HelloAndroid" android:label="@string/app_name"> <intent-filter> <action android:value="android.intent.action.MAIN" /> <category android:value="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> </manifest> The line 2 is a namespace declaration, which makes a standard Android attributes available for that application. In the line 4 there is a single <application> element, where the developer specifies all application level components and its properties used by the package. Activity class in the line 5 represents the initial screen the user sees and it may have one or more <intent-filter> elements to describe the actions that activity supports. There is an activityCreator script, which generates the following files and folders in the Eclipse workplace: - AndroidManifest.xml file discussed before; - Build.xml – an ant file which is used to package an application; - src/ - source directory - bin/ - the output directory 44 Service Discovery with the Google Android mobile platform 3.9 Security model In the Android Security architecture, a generic application has no permission to perform actions which may adversely impact the operating system or other applications. For instance, an application is not allowed to read or write user’s private data or read another application’s files. In other words, an application’s process could be considered a secure sandbox which are associated permissions. These permissions must be explicitly statically declared in the application from the developer, if he wants an activity, a process or anything else, to be able to perform actions which could harm the entire application, or other applications. The Static declaration is necessary because, once declared, the permissions can be known at install time and will not change after that. These permissions are handled by the operating system. Once described how the security model works, what application can do and what it cannot do, we will describe how it is possible to allow some “not permitted” actions with an example. Let’s assume that we want to allow an application to access to the network: the declaration of the permission would be: <uses-permission android:name="android.permission.INTERNET"></uses-permission> At application install time, permissions requested by the application are granted to it by the package installer, based on checks against the signatures of the applications declaring those permissions and/or interaction with the user. No checks with the user are done while an application is running: it either was granted a particular permission when installed, and can use that feature as desired, or the permission was not granted and any attempt to use the feature will fail without prompting the user [4]. 45 Service Discovery with the Google Android mobile platform 3.10 Android and the Service Discovery Since the Google Android mobile platform is quite a new technology, there is still lack of service discovery technologies ported on it. The first service, provided by Google at the launch of the first Android device, the HTC G1, has been the Android Market. Similar to the IPhone’s AppStore, this platform helps the developers to publish their applications, for free or with fee. An user interested to download an application can access to the Android Market through his mobile phone, search for the desired application and download it. However, the Android Market is not properly a service discovery mechanism, since it provides complete applications, rather than services that may be combined in order to obtain complex functionalities. As a real service discovery technology, recently the OSGi (Open Service Gateway initiative) service platform [9] has been ported on Google Android through the Apache Felix framework [10]. This has been an important step, since it shows that the interest of the developers on the Google Android mobile platform is more than focused and probably more other ports will follow in a not distant future. 46 Service Discovery with the Google Android mobile platform Chapter 4 Development of an Android-based Service Discovery application In this chapter we will discuss the design and the implementation of an Android-based Service Discovery application for the Core Framework. This application should make the user always able to keep up to date the services installed on his device and install new services when he needs. 4.1 Technical Requirements The application should allow the user to send a request to the server for the available services in the repository for his device and show them as a list in which the user can chose the desired one and, if not installed on his device, to download and install it. The Discovery application is designed according to the basic service discovery elements. 4.2 Design of the services Repository The services will be structured as directory trees. There will be: • A root directory for each OS supported by the framework’s services 47 Service Discovery with the Google Android mobile platform • A directory for each service • A directory for each version of the services The directory tree should appear as follows: Figure 4.1 - Repository Directory Tree A XML file called latest.xml will keep track of the latest version of the services for each OS. This file contains a field for each service with the version number and another field for each service with its description, as shown in Figure 4.2: Figure 4.2 – latest.xml 48 Service Discovery with the Google Android mobile platform 4.3 Design of the Discovery Service The following figure is shown the overall architecture of the Discovery Service: Figure 4.3 – Architecture It is clear that the application uses the Proxy Paradigm for the communications between client and server. The client application sends the request through a Stub. This request is coded and sent to the Skeleton on the server side. When the Skeleton gets the code, it calls the corresponding method on the Discovery Service. Since the framework provides just few services, the only research mechanism allowed is the browsing. In the following figure is shown the client side package structure: <<uses>> it.unina.discovery it.unina.discovery.util AsyncUA FileTransferer InterfaceStubDiscovery Interfaccia2 Discovery ServicesList ServiceDescription StubDiscovery Figure 4.4 – Client side package structure 49 Service Discovery with the Google Android mobile platform And next is shown the server side package diagram: local.socket DiscoveryService InterfaceSkeletonDiscovery SkeletonDiscovery Figure 4.5 – Server side package structure The client side class diagram is shown in the following figure: Figure 4.6 – Client side class diagram 50 Service Discovery with the Google Android mobile platform In this diagram are shown all the needed classes for the implementation of the client application, plus an utility class called FileTransferer which is used by the Stub to receive files from the server. In Figure 4.7 is shown the Server side class diagram: Figure 4.7 – Server side class diagram It includes the Skeleton with its own interface and the DiscoveryService, which represents the real service. In this application the server works as a Service Provider and there is not a registry. This is coherent with the framework paradigm, in which each device may become a Service Provider. 4.4 Implementation of the Discovery Service The Discovery service is made of two components: a server-side and a client-side one. 51 Service Discovery with the Google Android mobile platform The server-side component provides the service to the client, using a Skeleton interface which calls the methods on the service class when the client sends it a request through a Stub interface. 4.4.1 Server Side The main components of the Discovery Service’s server side are three: • A service interface • A proxy which handles the remote requests • The service itself The server side of the Discovery Service acts both as a Registry and as a Server Agent. In fact it is the Discovery Service itself that provides the services and publishes them. However, it is not excluded the possibility to implement applications (for Android, or other operating systems) which act as Server Agents and register their services on the Discovery Service. The interface is defined as follows: Figure 4.8 – Skeleton Interface 52 Service Discovery with the Google Android mobile platform This interface defines the methods which can be called on the service and the constants needed by the protocol in order to handle the requests and the results. The definition of an interface is needed, since the client application may be implemented using a different language and, in this case, it cannot call methods on a Java class. Thanks to the interface, the client application is able to send requests to the service using a Socket connection, and this makes the service independent from the language in which the application has been implemented. The requests are forwarded to the service through a Skeleton, which listens to the client application’s requests (sent through a Stub), and, depending on the received code, calls a method on the service itself. The Skeleton may be represented as follows: Figure 4.8 – Skeleton Class The Skeleton implements a run() method, since it is a thread, an always active daemon waiting for remote requests. Moreover the Skeleton calls the method on an instance of the Discovery service, using the handled object. This object is set up by the method setHandled(). The Notify() method is used by the Skeleton to send the results back to the Stub 53 Service Discovery with the Google Android mobile platform The whole communication logic is implemented in the run() method, which receives the requests from the client application, reads its parameters and calls the requested method on the handled object. Finally, the service is implemented in the following Java class: Figure 4.9 – Discovery Service The service basically implements two public methods: BrowseServices(): sends to the client a list of the latest versions of the available services for the client’s device, defined in an XML file called latest.xml. RequestService(): sends to the client the installation package for the client device (CAB for Windows Mobile, APK for Android, SIS for Symbian, etc.) These two public methods are quite similar in their implementation: they open a socket connection with the client and send the files (XML for the first one and installation package for the second one) to it, using the private SendFile() method. 4.4.2 Client Side The client side application of the Discovery Services acts as a Client Agents, since it asks to the remote server for a list of the available services and selects 54 Service Discovery with the Google Android mobile platform the desired one. It is composed of three parts: • A service interface • A proxy which handles the remote requests • The application itself It is clear that this application is a sort of mirror image of the server side component. The interface defines the methods that can be called on the service, in the same way of the server side interface. Figure 4.10 – Stub Interface This interface is implemented by the Stub, which sends the requests to the service Skeleton through socket connections. The Stub is fully charged of the communication with the server side application. In this way the user interface is independent from the business logic. The Stub is implemented as follows: 55 Service Discovery with the Google Android mobile platform Figure 4.11 – Stub Class As for the Skeleton, the Stub is implemented as a thread, so it has a run() method that defines the behavior of the Stub itself during its lifecycle. The method implementation is quite simple, since its role is just the reception of the Skeleton’s answers. The init() method initializes the socket connection with the Skeleton and starts the thread. On the other hand the halt() method stops the thread and closes the socket connection. The requests to the Skeleton are sent by the methods BrowseServices() and RequestService(), which send the corresponding code through the socket connection. The identifiers of the installed services on the device are stored in the services.xml file: an XML file similar to the latest.xml file. The structure of this file is shown in the following figure: 56 Service Discovery with the Google Android mobile platform Figure 4.12 – The services.xml file As the figure shows, the <services> section is identical to the latest.xml file. Moreover it includes a section describing the phone model and the operating system running on it. However, at the moment the service discovery is based just on the operating system, due to the difficulties for the emulator to simulate different phone models. The main application is implemented in three Activities. Figure 4.12 – Discovery main Activity 57 Service Discovery with the Google Android mobile platform Figure 4.13 – Discovery services list Activity Figure 4.14 – Discovery service description Activity In the main activity, shown in Figure 4.12, are implemented two important methods: CheckServiceandVersion() and UpdateXml(). The former checks if the requested service is already installed and, in this case, if it is updatable with a new version: this check is performed comparing the <services> sections of the services.xml and the latest.xml files. The latter, if a service has been installed or updated on the device, updates the services.xml file. The access and the parsing of the XML files is performed using the JDOM library: an Open Source library including a large amount of classes for the XML manipulation. The second activity, after the browsing request, shows a list of services available on the server, and allows to select one of them by clicking on it. The selection opens the third activity, which shows a description of the selected service and its version. This activity allows to select this service or discard it 58 Service Discovery with the Google Android mobile platform and return to the services list. If the service is selected, this selection is returned to the main activity and elaborated, as will be described in the next section. Finally, the AsyncUA interface (implemented by the Discovery activity) is used by the Stub in order to implement an asynchronous callback mechanism. 4.5 Interactions In this section we will show how the various components of the application interact. The first operation performed by the application is a service browsing request, sent by the main activity to the server, through the Stub. SkeletonDiscovery StubDiscovery Discovery DiscoveryService BrowseServices() (Socket) BROWSE_SERVICES BrowseServices() ReceiveFile() BrowseServices() SendFile() latest.xml Notify() Figure 4.15 – Service Browsing The main activity calls the BrowseServices() method on the Stub. This method sends to the Skeleton (through a socket connection), a message which tells it that the client wants to receive a list of the available services. This message is coded as an integer static and final variable called BROWSE_SERVICES. Along with the message, the 59 Service Discovery with the Google Android mobile platform Stub sends also the name of the OS running on the device, in order to allow the server to send a list of compatible services. When the Skeleton receives the message with the OS version, it invokes the BrowseServices() method on itself and the invocation is forwarded to the DiscoveryService through an upcall. As described in the previous section, the list of the latest versions of the available services is stored, for each operating system, in a XML file, called latest.xml. When the BrowseServices() method is called on the DiscoveryService, this one opens another socket connection with the Stub and sends the correct latest.xml file to it, through the SendFile() method. Meanwhile the Stub has already called the ReceiveFile() method and is waiting for the file itself. Once the file has been received (or if there have been problems in the file delivery), the Stub notifies it to the main activity calling the Notify() method on it, with a FILE_SENT (or a ERROR_SENDING_FILE) message as a parameter. A Toast (message box) will inform the user that the file has been received or not. At this point, if everything has gone well, the client application shows to the user the list of the available services in a list of items, selectable by clicking on them. When a click on an item is performed, the application opens a screen showing some informations about the corresponding service. These informations include the name of the services, the version and a short description. The user can select this service by clicking on a Select button or return to the services list by clicking on a Back button. The steps of a service request are shown in the following figure: 60 Service Discovery with the Google Android mobile platform StubDiscovery Discovery SkeletonDiscovery DiscoveryService (ServicesList) startActivity() Service selection (ServiceDescription) startActivity() CheckServiceAndVersion() RequestService() (Socket) REQUEST_SERVICE RequestService() ReceiveFile() RequestService() SendFile() Service APK file Notify() UpdateXml() Figure 4.16 – Service request After the client application has received the latest.xml file, it shows the services list to the user. In order to do so, it starts an activity, called ServicesList, which, as described before, shows a list of clickable items. When an item is selected, the ServicesList activity starts another activity, called ServiceDescription. This last activity shows a description of the selected service and allows the user to select it by clicking on the Select button. At this point the selection is returned to the main activity, which runs the CheckServiceAndVersion() method. The CheckServiceAndVersion() method compares the latest.xml file with the local 61 Service Discovery with the Google Android mobile platform services.xml files, in order to decide whether allow or not the user to download the requested service. In fact, there may exist three scenarios: • The service is not installed on the device. • The service is already installed on the device, but it is available a new version. • The service is already installed on the device and there are not new versions available. Obviously, in the third case, no further actions are performed. In the first and in the second case, instead, if the user decides to download the service, the main activity calls on the Stub the RequestService() method. As for the BrowseServices() method, a service request message will be sent to the Skeleton through a socket connection. The message is coded with a static and final integer variable, called REQUEST_SERVICE. Along with the message, the Stub sends the service name, the version and the OS for which the service has been requested. The Skeleton receives the message and calls a RequestService() method on itself and this invocation is upcalled to the DiscoveryService. The DiscoveryService, from the service name, version and OS, retrieves the correct APK file from the Repository and sends it to the Stub through the SendFile() method. Meanwhile, as for the services browsing, the Stub has already called the ReceiveFile() method and is waiting for the file. Once the file has been received (or if there have been problems in the file delivery), the Stub notifies it to the main activity calling the Notify() method on it, with a FILE_SENT (or a ERROR_SENDING_FILE) message as a parameter. A Toast (message box) will inform the user if the file has been received or not. At this point, if the file has been correctly received, the client application updates the services.xml file with the new service (or the new version of a service), through the invocation of the UpdateXml() method. 62 Service Discovery with the Google Android mobile platform Chapter 5 Examples of use In this chapter we will show some examples of use of the Android Discovery application. As described in the previous chapter, when the user selects a service, there may exist three possible scenarios: • The service is not installed on the device. • The service is already installed on the device, but there is a new version available on the server. • The service is already installed on the device. In the first section of this chapter we will be describe the main screen of the application. In the following three sections, instead, we will make some examples of use of the application and in each section will be shown one of the three scenarios. 63 Service Discovery with the Google Android mobile platform 5.1 The Main screen The main screen of the Discovery application appears as in Figure 5.1 Figure 5.1 – The Discovery application’s main screen As the figure shows, the main screen of the application is quite simple: it consists of just a Start button. By pressing this button, the user starts the services browsing. 5.2 Scenario 1: Selection of a not installed service In this scenario we will show how the user selects a not installed service and downloads it. In this section, and in the following ones, it will be assumed that the files between the client and the server will be transferred without errors. 64 Service Discovery with the Google Android mobile platform First of all the user clicks on the Start button in the main screen. As described in the previous chapter, the Stub will send the BROWSE_SERVICES message to the Skeleton and the Skeleton will call the BrowseServices() method on the DiscoveryService. After the DiscoveryService has sent the latest.xml file to the client, this will show to the user a list of the available services: Figure 5.2 – The services list The downloadable services are shown as a list of clickable items. Let’s assume that the user has installed on his device: • DroidMobiVoIP, version 0.9 • GPS, version 3.1 The user selects the IM item and the application will show a description of the 65 Service Discovery with the Google Android mobile platform service: Figure 5.3 – The service description The screen shows that IM is an Instant Messaging application and its version is 1.2. At this point, the user decides to get this service on his device and pushes the Select button. The application will return to the main screen, and, after the check, it will ask to the user if he wants to download it: 66 Service Discovery with the Google Android mobile platform Figure 5.4 – Download prompt The user will select Yes and, after the completion of the download, the application will inform the user that the file has been correctly downloaded and will update the services.xml file. 5.3 Scenario 2: Selection of an updatable service In this scenario, the user selects a service for which an update is available on the service. Let’s assume that the installed services are the same of the previous section. The user selects the GPS service and the application will show a description 67 Service Discovery with the Google Android mobile platform Figure 5.5 – The service description In this case, the available version of the service in the Repository is the 3.2 version. This version is more recent than the one installed on the device, so the user decides do download it. The application will inform the user that he is going to download a new version of the GPS service. 68 Service Discovery with the Google Android mobile platform Figure 5.6 – Download prompt The user will select Yes and, after the completion of the download, the application will inform the user that the file has been correctly downloaded and will update the services.xml file. 5.4 Scenario 3: Selection of an already installed service As a last scenario, we will see what happens if the users tries to download a service that is already installed on the device. Once again the installed services are the same of the previous sections. Let’s assume that the user selects the DroidMobiVoIP service. As in the previous examples, the application will show a description of the service: 69 Service Discovery with the Google Android mobile platform Figure 5.7 – The service description As the figure shows, the version of the DroidMobiVoIP application is the 0.9: the same installed on the device. However, the user clicks the Select button. The application will check the selection and realizes that the service is already installed on the device and it is updated to the latest version. With a message, it will notify this to the user: 70 Service Discovery with the Google Android mobile platform Figure 5.8 – Service already installed 71 Service Discovery with the Google Android mobile platform Conclusions In the rapid and continuous spreading of the mobile technologies, the Services Oriented Architectures represent a natural evolution for the applications. The mobile device is, for the user, a key to interact with the environment: with a wireless connection, the user may receive informations about the painting he is watching in a museum, or know the price of a product in a supermarket, or even receive the book list in the section of the library in which he is walking. In this scenario the relevance of the Service Discovery is not negligible. The user does not know a priori which service he is going to use, so he must be allowed to be informed on what he can do in the place where he is, and maybe to prefer a free service, rather than one with fee. With the launch of Android, Google Inc. has tried to define a new concept of mobile platform: • An easy environment with the availability of large amounts of applications for the users. • An Open Source operating system, with an intuitive and fully Java-based programming model for the developers. By now, Android mobile phones are sold only in United States and United Kingdom, but, in the first quarter of 2009, they will be launched also on the European market. 72 Service Discovery with the Google Android mobile platform By that date, due the larger amount of devices, companies will need to port their Client Agents for the service discovery on the Android platform. However, this would not be a hard work, since one of the best advantage of the Google Android mobile platform is its fully Java-based programming model. In fact, in this way the developers will be able to reuse the already available Java code, focusing their efforts just on the development of the User Interface. 73 Service Discovery with the Google Android mobile platform Future Works The Discovery application, by now, is provided of the basic functionalities for the service discovery. In the future this application may be enriched with a set of other functionalities, like the ability to scan the area in search of more than one discovery server. In this way the user may be able to get the selected service from a server, rather than another one, with a consequent reduction of the overhead, since the user would select the less charged server, or to select different implementations of the same service (i.e. a free one or one with fee). Moreover, the current implementation of the Discovery application just downloads the service. A possible function to implement in the future is a dialog box which asks to the user if he wants to automatically install and execute the new service. Finally, as discussed in the fourth chapter, since by now the framework has been designed for a small number of services, the only search mechanism implemented in the Discovery application is the browsing. However, it is not excluded that some companies interested in the use of the framework will implement a remarkable number of services. So, it is advisable a future implementation of other search mechanisms, as by class or by specific name. 74 Service Discovery with the Google Android mobile platform Appendix A How to install the Android environment on Eclipse The easiest way to develop an Android application is using the plug-in provided by Google for Eclipse. In order to do so, first of all we need to download the Android SDK and unpack it in a directory on which we have full access rights (on Linux or Mac it may be the home directory). After this we have to download the Eclipse plug-in. It may installed using the Eclipse update manager, as shown in Figure A.1. Figure A.1 – The Eclipse update manager 75 Service Discovery with the Google Android mobile platform In order to get the plug-in we must add the remote site: https://dl-ssl.google.com/android/eclipse/ Now we have to configure the plug-in. This may be done selecting Window > Preferences and selecting Android from the left panel. Figure A.2 – The Android configuration panel 76 Service Discovery with the Google Android mobile platform Appendix B Creating a first simple Android application In this section we will discuss the development of a first simple Android application. It is the Android version of the classic “Hello World” application, well known to those who are introduced for the first time to a programming language. As a first step, we have to create a new project in Eclipse and select Android Project in the Android folder (it should be available if the plug-in has been installed correctly). Figure B.1 – Creating a new Android Project 77 Service Discovery with the Google Android mobile platform In Figure B.2 is shown the configuration window for the new project: Figure B.2 – Android Project configuration window The fields are the followings: • Project name: the name of the directory in which the project files will be stored. • Package name: this is the package namespace (following the same rules as for packages in the Java programming language) that we want all our source code to reside under. This also sets the package name under which the stub Activity will be generated. The package name we use in our application must be unique across all packages installed on the system. For this reason, it's very important to use a standard domain-style package for the applications. In the example above, we used the package domain "com.android". 78 Service Discovery with the Google Android mobile platform • Activity name: this is the name for the class stub that will be generated by the plugin. This will be a subclass of Android's Activity class. An Activity is simply a class that can run and do work. It can create a UI if it chooses, but it doesn't need to. • Application name: is the human-readable title for the application. Once the project is created, the HelloAndroid.java class will be generated. package com.google.android; import android.app.Activity; import android.os.Bundle; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); } } Now we can modify it: package com.google.android; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); TextView tv = new TextView(this); tv.setText("Hello, Android"); setContentView(tv); } } In Android, user interfaces are composed of hierarchies of classes called Views. A View is simply a drawable object, such as a radio button, an animation, or (in our case) a text label. The specific name for the View subclass that handles text is simply TextView. Here's how you construct a TextView: TextView tv = new TextView(this); The argument to TextView's constructor is an Android Context instance. The Context is simply a handle to the system: it provides services like resolving resources, obtaining access to databases and preferences, and so on. The Activity class inherits from Context. Since our 79 Service Discovery with the Google Android mobile platform HelloAndroid class is a subclass of Activity, it is also a Context, and so we can pass the 'this' reference to the TextView. Once we've constructed the TextView, we need to tell it what to display: tv.setText("Hello, Android"); At this point, we've constructed a TextView and told it what text it has to display. The final step is to connect this TextView with the on-screen display, like so: setContentView(tv); The setContentView() method on Activity indicates to the system which View should be associated with the Activity's UI. If an Activity does not call this method, no UI is present at all and the system will display a blank screen. For our purposes, all we want is to display some text, so we pass it the TextView we just created. Now we can run our project. We can create a Run Configuration as shown in Figure B.3: Figure B.3 – The Run Dialog 80 Service Discovery with the Google Android mobile platform The output of the emulator will be as follows: Figure B.4 – Hello Android 81 Service Discovery with the Google Android mobile platform Appendix C Creating an application with a complex UI In this section we will show how to create an application with a more complex UI than a TextView. As shown in the third chapter, the User Interface of an Android application may be written using the XML language. However, writing the whole code by hand is quite tedious, so we will use a tool called DroidDraw, a WYSIWYG (What You See Is What You Get) tool which allows to create UIs by drag&drop and then generate the corresponding XML code. The tool (which is Java-based) can be accessed directly online at the site: http://www.droiddraw.org/ or it is possible to download the standalone executable for Windows, Linux and Mac OS X. As a first step, we set the root layout to RelativeLayout: Figure C.1 – Layout selection 82 Service Discovery with the Google Android mobile platform Select the Layouts tab. Figure C.2 – The Layouts tab Drag and drop a LinearLayout object from the Layouts panel into the top-center of the screen Figure C.3 – LinearLayout selection Select the LinearLayout object and click on the properties tab to begin editing the layout properties. Change the width to "200px" and the height to "130px" Press Apply to apply your changes. Figure C.4 – LinearLayout properties Go to the Widgets tab. 83 Service Discovery with the Google Android mobile platform Figure C.5 – The Widgets tab Drag and drop two TextView objects and two EditText objects into the LinearLayout so that they alternate. Figure C.6 – The UI preview Drag and drop a RadioGroup object into the LinearLayout. Drag and drop two RadioButton objects into the RadioGroup. 84 Service Discovery with the Google Android mobile platform Figure C.7 – The UI with the RadioButtons Drag and drop a Button object into the root RelativeLayout below the LinearLayout object. It should align with the right edge of the LinearLayout. Figure C.8 – The complete UI preview Edit the properties of each TextView object. Make text for the upper one read Dollars and make its style bold. Make the lower one read: Euros and make its style bold also. Edit the properties of the upper EditText as follows: • Change the id to read: "@+id/dollars" • Change the text to be empty • Change the width to be "100px". 85 Service Discovery with the Google Android mobile platform Repeat this last step with the second EditText under the Euros TextView, but make the id be "@+id/euros" Edit the first RadioButton so that its text reads: Dollars to Euros and its id is "@+id/dtoe". Edit the second RadioButton so that its text reads: Euros to Dollars and its id is "@+id/etod". Important Note: We must get the ids exactly correct, because this is how we will look up the widgets in source code. Edit the Button so that its text reads: Convert and its id is "@+id/convert". The final GUI should look like as follows: Figure C.9 – The final UI Press the Generate button to generate the layout XML. In Eclipse create a new android project. Copy and paste the XML from DroidDraw to replace the contents of res/layout/main.xml At this point we should be able to run our GUI in Android. It should look something like this: 86 Service Discovery with the Google Android mobile platform Figure C.10 – The running GUI The last step is to actually code the currency conversion. It is possible to look up the GUI elements with: this.findViewById(R.id.<id>). Here is the complete code for the CurrencyConverter activity: 87 Service Discovery with the Google Android mobile platform import import import import import import import android.app.Activity; android.os.Bundle; android.view.View; android.view.View.OnClickListener; android.widget.Button; android.widget.RadioButton; android.widget.TextView; public class CurrencyConverter extends Activity implements OnClickListener { TextView dollars; TextView euros; RadioButton dtoe; RadioButton etod; Button convert; /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); dollars = (TextView)this.findViewById(R.id.dollars); euros = (TextView)this.findViewById(R.id.euros); dtoe = (RadioButton)this.findViewById(R.id.dtoe); dtoe.setChecked(true); etod = (RadioButton)this.findViewById(R.id.etod); convert = (Button)this.findViewById(R.id.convert); convert.setOnClickListener(this); } public void onClick(View v) { if (dtoe.isChecked()) { convertDollarsToEuros(); } if (etod.isChecked()) { convertEurosToDollars(); } } protected void convertDollarsToEuros() { double val = Double.parseDouble(dollars.getText().toString()); // in a real app, we'd get this off the 'net euros.setText(Double.toString(val*0.67)); } protected void convertEurosToDollars() { double val = Double.parseDouble(euros.getText().toString()); // in a real app, we'd get this off the 'net dollars.setText(Double.toString(val/0.67)); } } 88 Service Discovery with the Google Android mobile platform References [2] M. Cinque, “Il discovery dei servizi in ambienti di nomadic computing: un approccio integrato” [3] V. Alfieri, “Implementazione di un servizio VoIP in ambienti SOA per mobile [1] Jerome Di Marzio, 2007, “Android – A Programmer’s Guide” computing” [4] http://code.google.com/android [5] http://en.wikipedia.org/ [6] http://www.anddev.org/ [7] Sun Microsystems, Jini Network Tecnology, http://www.sun.com/jini [8] Gryazin. Service Discovery in Bluetooth. Dept. Of Computer Science, Helsinky University of Technology. 2000 [9] Murples, Kriens. The Open Service Gateway initiative: an introductory overview. IEEE Communication Magazine. 2002 [10] Offermans, Pauls. OSGi on Google Android using Apache Felix [11] http://felix.apache.org 89