Deep Inside Android OpenExpo 2008 - Zurich September 25 th, 2008 Copyright 2007 Esmertec AG Jan 2007 Gilles Printemps - Senior Architect
Agenda What is Android? The Android platform Anatomy of an Android application Creating and deploying an application Esmertec Proprietary OpenExpo 2008 Page 2
What is Android? A complete software stack for mobile devices. Introducing Android A first joined project of the Open Handset Alliance (OHA). First open, complete and free platform Software stack open-sourced under Apache 2.0 license Source code will be available and everyone will have the capability to built an image The Android platform It includes an operating system, a middleware and some applications. Lightweight and full featured Developers can extend and replace existing components A generous development environment A SDK is available to build, compile, test and debug user applications. ations. Applications are developed using Java programming language No difference between the built-in in applications and the user ones Esmertec Proprietary OpenExpo 2008 Page 3
Agenda What is Android? The Android platform Linux Kernel Native Libraries Android Runtime Application Framework Anatomy of an Android application Creating and deploying an application Esmertec Proprietary OpenExpo 2008 Page 4
Linux Kernel Linux Kernel Display Driver Camera Driver Bluetooth Driver Shared Memory Driver Binder (IPC) Driver USB Driver Keypad Driver WiFi Driver Audio Drivers Power Management A Linux 2.6.24 fit for Android Some common features have been removed No GBLIC support No native windowing system Does not include the full set of Linux utilities New Android specific components have been added Alarm, Android Shared Memory Kernel Memory Killer,, Kernel Debugger, Logger Esmertec Proprietary OpenExpo 2008 Page 5
Linux Kernel (cont.) Power Management Based on the standard Linux Power Management, Android has its own n component. Application uses user space library to inform the framework about its constrains. Constraints are implemented using lock mechanism. Partial Wake Lock CPU Screen Keyboard Full Wake Lock Binder Driver to facilitate inter-process communication between applications and services. A pool of threads is associated to each application to process incoming IPC The driver performs mapping of object between two processes Binder uses an object reference as an address in a process s s memory space Application A Function(Object) Binder - Marshaling - Relaying Application B Thread Esmertec Proprietary OpenExpo 2008 Page 6
Native Libraries Native Libraries Linux Kernel Surface Manager Media Framework SQLite Open GL/ES WebKit SGL Libc SSL FreeType Android Libc implementation A custom implementation, optimized for embedded use. BSD license Small size and fast code paths Very fast custom pthread implementation Built-in in support for android-specific services (system properties, log capabilities) Doesn t t support some POSIX features Esmertec Proprietary OpenExpo 2008 Page 7
Native Libraries (cont.) Storage, rendering, multimedia, Provides the main features on the Android platform: SQLite,, a simple relational database management system (No IPC, single file, ) WebKit,, an application framework that provides foundation for building a web browser Media Framework,, based on PacketVideo opencore platform (codec) Optimized 2D/3D graphic library based on OpenGL ES Surface Manager Provides a system-wide surface composer to render all the surfaces in a frame buffer. Can combined 2D and 3D surfaces Can use OpenGL ES and 2D hardware accelerator for its compositions ons 7:56 PM App 1 7:56 PM Surface Manager Flinger App 2 Esmertec Proprietary OpenExpo 2008 Page 8
Native Libraries (cont.) Audio Manager Processes multiple audio streams into PCM audio out paths. Handle several types of devices (headphone, ear piece, ) Redirects audio stream to the specified output App 1 Media Player Audio Manager Manager ear piece App 12 Tone Audio headphone Hardware Abstraction Libraries Defines the interface that Android requires hardware drivers to implement. Set of standardized APIs the developer will have to implement Available for all the components a manufacturer can integrate on its Android platform Graphics Audio Camera Bluetooth GPS Radio Esmertec Proprietary OpenExpo 2008 Page 9
Android Runtime Android Runtime Native Libraries Linux Kernel Surface Manager Media Framework SQLite Open GL/ES WebKit Audio Manager Libc SSL FreeType Core Libraries Virtual Machine Dalvik Virtual Machine An interpreter-only virtual machine (no JIT), register based. Optimized for low memory requirements Designed to allow multiple VM instances to run at one Relying on underlying OS for process isolation, memory management nt and threading support Executes Dalvik Executables (DEX) files which are zipped into an Android Package (APK) Esmertec Proprietary OpenExpo 2008 Page 10
Application Framework Application Framework Android Runtime Native Libraries Linux Kernel Manager Window Manager Content Providers View System Notification Manager Package Manager Telephony Manager Resource Manager Location Manager Some essential services However, home made applications don t t interact directly with them. Manager handles application lifecycle Package Manager holds information about applications loaded in the system Windows Manager handles all the application related windows View system provides all the standard widgets to build an application Hardware services provide access to lower-level level hardware APIs: Bluetooth, telephony, location, Esmertec Proprietary OpenExpo 2008 Page 11
Platform initialization Kernel Init The bootloader loads the kernel and starts the init process daemons Zygote Runtime Service Manager Daemons for handling low level hardware interfaces are started up (usb, adb, debugger, radio) Zygote, the initial Dalvik VM process is created Runtime process initiates the Service Manager, a key element for Binders and IPC communication Dalvik VM System Server Runtime process requests Zygote to start a new instance of Dalvik for running the System Server Surface Manager Audio Manager Registration The two first processes are able to handle graphic and audio outputs Telephony Bluetooth Manager Package Manager Service Manager All the others android components are then started Esmertec Proprietary OpenExpo 2008 Page 12
Agenda What is Android? The Android platform Anatomy of an Android application Service Content Provider Processes and Tasks Creating and deploying an application Esmertec Proprietary OpenExpo 2008 Page 13
One single screen in an Android application What is really an? Displays a user interface component and responds to system/user initiated. When an application has a user interface, it contains one or more Activities One activity is then considered as the main entry point by the system An existing can be replaced with a new one that fulfill the same contract Each can be invoked from others applications Adding a new in an Android project The new Java class must extend the framework class Created must be defined into the application s s Manifest <activity android:name=.sample android:label= @string/app_name > </activity> Class name Esmertec Proprietary OpenExpo 2008 Page 14
Lifecycle Android maintains an history stack of all the activities which are spawned in an application A Classic scenario An is started and explicitly finalized (i.e. finish() is called). OnCreate() First method called during lifetime; the is created Initialize all the resources (i.e. create a thread, connection to a database) Start up OnStart() Execution of the can start at anytime; system put it on top of the stack is on-screen (may be not in foreground); user cannot interact with. OnResume() is visible to the user and has the focus. OnPause() Focus is lost and potentially the will shutdown Save data (persistence) Shutdown OnStop() is no more on the top of the stack Service OnDestroy() Manager does not exist anymore in the system Resources can be freed Esmertec Proprietary OpenExpo 2008 Page 15
Lifecycle (cont.) Switching between Activities Android will notify the running through two new callbacks. OnFreeze() OnResume() OnPause() OnStop() OnStart() OnRestart() On Freeze(): All the to save UI state Save the value belonging to the UI (i.e. field in a form) On Restart(): Signal the will be restarted Dropping an An can be dropped from memory only in the following specific states: s: When it is paused, even if it is completely alive When it is completely obscured by another (stopped) Normal Execution OnStop() OnDestroy() The system can: - Ask the user to finish it - Directly kill the process it belongs to OnCreate() Esmertec Proprietary OpenExpo 2008 Page 16
Navigation and Triggering Intents / Intent Filters Simple message objects that represent: An intention to do something A declaration of capacity and interest in offering assistance to those in need MP3 Player Manager - Edit / Create a play list - View a play list Intents - Build a play list - Listen one play list Service IntentFilters - Play a MP3 file An intent is made up a number of pieces of information describing the action or the service: action attribute is typically a verb (VIEW( VIEW, EDIT, DIAL, ) The data to operate on is expressed in the form of an Universal Resource Identifier (URI) category attribute gives additional information about the action to execute <intent-filter> <action android:value= android.intent.action.view /> <data android:mimetype= com.esmertec.player/media/12 /> </intent-filter> Esmertec Proprietary OpenExpo 2008 Page 17
Broadcast Intent Receiver Broadcasted notifications from the system When using these Receivers? When an application desires to receive and respond to a global event. e In order to be triggered when an event occurs, application does not have to be running By default, Android includes some built-in in Intents Receiver Alerter Manager - Get incoming calls - Get incoming SMS How to receive these specific Intents? The user class must extend the framework IntentReceiver class To process incoming Intents, onreceiveintent() onreceiveintent() method is implemented receiver element must be described into the application s s Manifest <receiver android:name=.alerter > Class name <intent-filter> <action android:name= android.provider.telephony.sms_received /> </intent-filter> </receiver> Esmertec Proprietary OpenExpo 2008 Page 18
Service A long-running background task Defining and invoking a Service Adding a Service with Android is quite similar than for an. Framework Service class must be extended The new Service must be defined into the application s s Manifest <service class=".adderserviceimpl"/> Class name When a Service is using IPC, an AIDL description of its features is also needed. d. Android Interface Definition Language (AIDL) is used to generated ed code to allow communication between two processes through IPC This mechanism is interface-based, similar to Corba (Unix) or COM (windows) but lighter weight With this specific mode, the Service is started through the binder and not with startservice() startservice() Manager Start Service Notification Communication Binder Esmertec Proprietary OpenExpo 2008 Page 19
Content Provider Handle data and expose them to other applications Why using a Content Provider? The only way to share data between Android applications. It implements a standard set of methods to allow access to a data store Any form of data storage can be used like SQLite database, files, or memory hash map APK APK Content Provider Service Data SQLite XML Remote Store A Content Providers exposes a unique URI used to query, add, update and delete data: A standard prefix ( content://( content:// ) The authority part (fully-qualified to ensure uniqueness) The path to determine what kind of data is being requested A specific record being requested, if any Esmertec Proprietary OpenExpo 2008 Page 20
Processes and Tasks A relation between the kernel and Android APK Task APK P1 Content Provider Content Provider P2 Service Service P3 Processes A low-level level kernel process in which an application s s code is running. By default, Android binds the content of an APK to a Linux process Process tag can be used to tune this relation with a lower granularity (activity, service, ) Tasks A notion that users know on other platform as application. A collection of related Activities Capable of spanning multiple processes Interaction with Activities can be controlled through s s launchmode attribute Esmertec Proprietary OpenExpo 2008 Page 21
Agenda What is Android? The Android platform Anatomy of an Android application Creating and deploying an application Eclipse plug-in Building the package Running the application Debugging environment Esmertec Proprietary OpenExpo 2008 Page 22
Creating an Application Using the Eclipse plug-in After some clicks, a basic application can be created, compiled and executed. Only some properties are required to create an Android skeleton The plug-in creates all the file/directories useful to generate the final APK It can be freely downloaded by following the instructions at http://code.google.com/android/intro/installing.html OpenExpo XML AndroidManifest res com.esmertec. openexpo Resources Java Sample An element of a complete development environment containing: An Android emulator which mimics the hardware and the software of a mobile phone Some tools for debugging, tracing, logging Esmertec Proprietary OpenExpo 2008 Page 23
Creating an Application (cont.) AndroidManifest.xml file Describes the application components that the package exposes. This file is mandatory and is located at the root of the application directory A top-level application presented to the user must include at least one that supports the MAIN action and LAUNCHER category XML AndroidManifest <?xml version= 1.0 encoding= utf-8?> <manifest xmlns:android= http://schemas.android.com/apk/res/android package= com.esmertec.openexpo android:versioncode= 1 android:versionname= 1.0.0 > <application android:icon= @drawable/icon android:label= @string/app_name > <activity android:name=.sampleapp android:label= @string/act_name > <intent-filter> <action android:name= android.intent.action.main /> <category android:name= android.intent.category.launcher /> </intent-filter> </activity> </application> </manifest> res XML values string drawable icon <?xml version= 1.0 encoding= utf-8?> <resources> <string name= act_name > Sample </string> <string name= app_name > Android Application </string> </resources> Copyright 2007 Esmertec AG Esmertec Proprietary OpenExpo 2008 Jan 2007 Page 24
Building an APK Dalvik Executable (DEX files) A optimized format for efficient storage and memory mappable definition. All classes are compiled with a standard Java language compiler Migration between a standard class file and the Android bytecode is done with the dx tool (For debugging purpose, it can also present a people-friendly readable format) AIDL *. AIDL *. Java *. Java *. Class DEX Application XML Manifest res JAR Java Android R Generating the Android specific java files: When an application contains IPC services, AIDL files must be preprocessed to get Java classes Interface based AIDL tool saves developer the time used to write marshalling code All Android projects have a resource ID file called R.java It s basically a series of integers that can be used to reference the actual resources This file is generated automatically by aapt and should not be edited Copyright 2007 Esmertec AG Esmertec Proprietary OpenExpo 2008 Jan 2007 Page 25
Building an APK (cont.) Packaging the resources During the build process, an archive containing application resources is also created. This file is automatically generated by the aapt utility Among other things, it s made up of an index resource file called resources.arsc ARSC XML Manifest res resources res JAR ap_ Android resources XML Manifest Generating the Android PacKage (APK) Typically, an APK includes all the files related to a single Android application: A compressed collection of AndroidManifest.xml, application code, resources Additionally, META_INF directory can integrate certificates used to sign application ARSC DEX resources ap_ Resources DEX Package XML Copyright 2007 Esmertec AG Esmertec Proprietary OpenExpo 2008 res Manifest META-INF Jan 2007 Page 26
Running the application Installing / Removing a package All Android applications are handled by the Package Manager. An APK must just be uploaded to a specific directory Two locations are monitored: /data/app (user) and /system/app (system) data Package Manager app Package Android Debug Bridge (ADB) A client/server application used as a gateway to communicate with the device. It allows: Copying files to/from the device or the emulator ( push, pull, install ) Running shell binary commands adb adbd Commands Commands Copyright 2007 Esmertec AG Esmertec Proprietary OpenExpo 2008 Jan 2007 Page 27
Debugging environment Dalvik Debug Monitor Service (DDMS) A GUI application providing debugging information to Android developers: Processes and threads examination Memory heap statistics and allocation tracker Emulator controls to simulate specific device events File explorer to perform basic management on the file system Dump of the printed out messages, Esmertec Proprietary OpenExpo 2008 Page 28
Esmertec Proprietary OpenExpo 2008 Page 29