1 / 106

Android Architecture

Android Architecture. Android Operating System. OS Components. Linux Kernel

evadne
Download Presentation

Android Architecture

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Android Architecture

  2. Android Operating System

  3. OS Components • Linux Kernel Android relies on Linux version 2.6 for core system services such as security, memory management, process management, network stack, and driver model. The kernel also acts as an abstraction layer between the hardware and the rest of the software stack.

  4. OS Components Android Runtime • Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language. • Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. • Dalvik has been written so that a device can run multiple VMs efficiently.

  5. OS Components Android Runtime • The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. • The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included "dx" tool. • The Dalvik VM relies on the Linux kernel for underlying functionality such as threading and low-level memory management.

  6. OS Components Libraries • Android includes a set of C/C++ libraries used by various components of the Android system. These capabilities are exposed to developers through the Android application framework. Some of the core libraries are listed below: • System C library - a BSD-derived implementation of the standard C system library (libc), tuned for embedded Linux-based devices • Media Libraries - based on PacketVideo'sOpenCORE; the libraries support playback and recording of many popular audio and video formats, as well as static image files, including MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG • Surface Manager - manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers from multiple applications

  7. OS Components Libraries • LibWebCore - a modern web browser engine which powers both the Android browser and an embeddable web view • SGL - the underlying 2D graphics engine • 3D libraries - an implementation based on OpenGL ES 1.0 APIs; the libraries use either hardware 3D acceleration (where available) or the included, highly optimized 3D software rasterizer • FreeType - bitmap and vector font rendering • SQLite - a powerful and lightweight relational database engine available to all applications

  8. OS Components Application Framework • Developers are free to take advantage of the device hardware, access location information, run background services, set alarms, add notifications to the status bar, and much, much more. • Developers have full access to the same framework APIs used by the core applications. The application architecture is designed to simplify the reuse of components; any application can publish its capabilities and any other application may then make use of those capabilities (subject to security constraints enforced by the framework). This same mechanism allows components to be replaced by the user.

  9. OS Components Application Framework • Underlying all applications is a set of services and systems, including: • A rich and extensible set of Views that can be used to build an application, including lists, grids, text boxes, buttons, and even an embeddable web browser • Content Providers that enable applications to access data from other applications (such as Contacts), or to share their own data • A Resource Manager, providing access to non-code resources such as localized strings, graphics, and layout files • A Notification Manager that enables all applications to display custom alerts in the status bar • An Activity Manager that manages the lifecycle of applications and provides a common navigation backstack

  10. Application Fundamentals • Android applications are written in the Java programming language. • The compiled Java code — along with any data and resource files required by the application — is bundled by the aapt tool into an Android package, an archive file marked by an .apk suffix. • This file is the vehicle for distributing the application and installing it on mobile devices; it's the file users download to their devices. All the code in a single .apk file is considered to be one application.

  11. Application Fundamentals • By default, every application runs in its own Linux process. Android starts the process when any of the application's code needs to be executed, and shuts down the process when it's no longer needed and system resources are required by other applications. • Each process has its own virtual machine (VM), so application code runs in isolation from the code of all other applications.

  12. Application Fundamentals • By default, each application is assigned a unique Linux user ID. Permissions are set so that the application's files are visible only to that user and only to the application itself — although there are ways to export them to other applications as well. • It's possible to arrange for two applications to share the same user ID, in which case they will be able to see each other's files. To conserve system resources, applications with the same ID can also arrange to run in the same Linux process, sharing the same VM.

  13. Application Components • An Android application can make use of elements of other applications. If your application needs to display a scrolling list of images and another application has developed a suitable scroller and made it available to others, you can call upon that scroller to do the work. • Your application simply starts up that piece of the other application when the need arises.

  14. Application Components • The system must start an application process when any part of it is needed, and instantiate the Java objects for that part. Android applications don't have a single entry point (no main() function). • Android applications have essential components that the system can instantiate and run as needed.

  15. Four Component Types Activities • Present a visual user interface for one focused endeavor the user can undertake. • Example - Present a list of menu items users can choose from or it might display photographs along with their captions. • Example - A text messaging application might have one activity that shows a list of contacts to send messages to, a second activity to write the message to the chosen contact, and other activities to review old messages or change settings.

  16. Activities • Each activity is independent of the others. • Each one is implemented as a subclass of the Activity base class. • Typically, one of the activities is marked as the first one that should be presented to the user when the application is launched. • Moving from one activity to another is accomplished by having the current activity start the next one.

  17. Four Component Types Activities • The visual content of the window is provided by a hierarchy of views — objects derived from the base View class. • Each view controls a particular rectangular space within the window. Parent views contain and organize the layout of their children. • Leaf views (those at the bottom of the hierarchy) draw in the rectangles they control and respond to user actions directed at that space.

  18. Activity Views • Views are where the activity's interaction with the user takes place. A view might display a small image and respond when the user taps that image. • Android has a number of ready-made views that you can use — including buttons, text fields, scroll bars, menu items, check boxes, and more. • A view hierarchy is placed within an activity's window by the Activity.setContentView() method. • The content view is the View object at the root of the hierarchy.

  19. Four Component Types Services • A service doesn't have a visual user interface, but rather runs in the background for an indefinite period of time. • Each service extends the Service base class. • A good example of a service is a media player playing songs. One or more player activities would allow the user to choose songs and start playing them. The music playback itself would not be handled by an activity (users will expect the music to keep playing ). The media player activity could start a service to run in the background.

  20. Services • It's possible to connect to (bind to) an ongoing service (and start the service if it's not already running). While connected, you can communicate with the service through an interface that the service exposes. For the music service, this interface might allow users to pause, rewind, stop, and restart the playback. • Like activities and the other components, services run in the main thread of the application process. So that they won't block other components or the user interface, they often spawn another thread for time-consuming tasks (like music playback).

  21. Four Component Types Broadcast receivers • A broadcast receiver is a component that does nothing but receive and react to broadcast announcements. • Many broadcasts originate in system code — for example, announcements that the timezone has changed, that the battery is low, that a picture has been taken, or that the user changed a language preference. • Applications can also initiate broadcasts — for example, to let other applications know that some data has been downloaded to the device and is available for them to use.

  22. Broadcast Receiver • An application can have any number of broadcast receivers to respond to any announcements it considers important. All receivers extend the BroadcastReceiver base class. • Broadcast receivers do not display a user interface. However, they may start an activity in response to the information they receive, or they may use the NotificationManager to alert the user. • Notifications can get the user's attention in various ways — flashing the backlight, vibrating the device, playing a sound, and so on. They typically place a persistent icon in the status bar, which users can open to get the message.

  23. Four Component Types Content providers • A content provider makes a specific set of the application's data available to other applications. The data can be stored in the file system, in an SQLite database, or in any other manner that makes sense. • The content provider extends the ContentProvider base class to implement a standard set of methods that enable other applications to retrieve and store data of the type it controls. • Applications do not call these methods directly. Rather they use a ContentResolver object and call its methods instead. A ContentResolver can talk to any content provider; it cooperates with the provider to manage any interprocess communication that's involved.

  24. Activating components: intents • Content providers are activated when they're targeted by a request from a ContentResolver. • Activities, services, and broadcast receivers — are activated by asynchronous messages called intents. • An intent is an Intent object that holds the content of the message.

  25. Intents • For activities and services, the Intent names the action being requested and specifies the URI of the data to act on. For example, it might convey a request for an activity to present an image to the user or let the user edit some text. • For broadcast receivers, the Intent object names the action being announced. For example, it might announce to interested parties that the camera button has been pressed.

  26. Methods for Activating an Activity • An activity is launched (or given something new to do) by passing an Intent object to Context.startActivity() or Activity.startActivityForResult(). • The responding activity can look at the initial intent that caused it to be launched by calling its getIntent() method. • Android calls the activity's onNewIntent() method to pass it any subsequent intents.

  27. Methods for Activating an Activity • One activity often starts the next one. If it expects a result back from the activity it's starting, it calls startActivityForResult() instead of startActivity(). For example, if it starts an activity that lets the user pick a photo, it might expect to be returned the chosen photo. The result is returned in an Intent object that's passed to the calling activity's onActivityResult() method.

  28. Methods for Activating a Service • A service is started (or new instructions are given to an ongoing service) by passing an Intent object to Context.startService(). • Android calls the service's onStart() method and passes it the Intent object. • Similarly, an intent can be passed to Context.bindService() to establish an ongoing connection between the calling component and a target service. The service receives the Intent object in an onBind() call. (If the service is not already running, bindService() can optionally start it.)

  29. Methods for Activating a Service • For example, an activity might establish a connection with the music playback service mentioned earlier so that it can provide the user with the means (a user interface) for controlling the playback. The activity would call bindService() to set up that connection, and then call methods defined by the service to affect the playback. • An application can initiate a broadcast by passing an Intent object to methods like Context.sendBroadcast(), Context.sendOrderedBroadcast(), and Context.sendStickyBroadcast() in any of their variations. • Android delivers the intent to all interested broadcast receivers by calling their onReceive() methods.

  30. Shutting down components • Content providers and broadcast receivers don’t need to be explicitly shut down. • A content provider is active only while it's responding to a request from a ContentResolver. • A broadcast receiver is active only while it's responding to a broadcast message. • Activities, on the other hand, provide the user interface. They're in a long-running conversation with the user and may remain active, even when idle, as long as the conversation continues. • Services may also remain running for a long time. Android has methods to shut down activities and services in an orderly way.

  31. Shutting down components • An activity can be shut down by calling its finish() method. One activity can shut down another activity (one it started with startActivityForResult()) by calling finishActivity(). • A service can be stopped by calling its stopSelf() method, or by calling Context.stopService(). • Components might also be shut down by the system when they are no longer being used or when Android must reclaim memory for more active components.

  32. The Manifest File • Before Android can start an application component, it must learn that the component exists. Therefore, applications declare their components in a manifest file that's bundled into the Android package, the .apk file that also holds the application's code, files, and resources. • The manifest is a structured XML file and is always named AndroidManifest.xml for all applications. • It does a number of things in addition to declaring the application's components, such as naming any libraries the application needs to be linked against (besides the default Android library) and identifying any permissions the application expects to be granted.

  33. Example Manifest with Activity <?xml version="1.0" encoding="utf-8"?><manifest . . . >    <application . . . >        <activity android:name="com.example.project.FreneticActivity"android:icon="@drawable/small_pic.png"android:label="@string/freneticLabel"                   . . .  >        </activity>        . . .    </application></manifest> • The name attribute of the <activity> element names the Activity subclass that implements the activity. • The icon and label attributes point to resource files containing an icon and label that can be displayed to users to represent the activity.

  34. Example Manifest with Activity <?xml version="1.0" encoding="utf-8"?><manifest . . . >    <application . . . >        <activity android:name="com.example.project.FreneticActivity"android:icon="@drawable/small_pic.png"android:label="@string/freneticLabel"                   . . .  >        </activity>        . . .    </application></manifest> • The other components are declared in a similar way — <service> elements for services, <receiver> elements for broadcast receivers, and <provider> elements for content providers. • Activities, services, and content providers that are not declared in the manifest are not visible to the system and are consequently never run. • Broadcast receivers can either be declared in the manifest, or they can be created dynamically in code (as BroadcastReceiver objects) and registered with the system by calling Context.registerReceiver().

  35. Intent Filters • An Intent object can explicitly name a target component. If it does, Android finds that component (based on the declarations in the manifest file) and activates it. • If a target is not explicitly named, Android must locate the best component to respond to the intent. • Android does so by comparing the Intent object to the intent filters of potential targets. • A component's intent filters inform Android of the kinds of intents the component is able to handle. Like other essential information about the component, they're declared in the manifest file.

  36. Intent Filters in a Manifest <?xml version="1.0" encoding="utf-8"?><manifest . . . >    <application . . . >        <activity android:name="com.example.project.FreneticActivity"android:icon="@drawable/small_pic.png"android:label="@string/freneticLabel"                   . . .  >            <intent-filter . . . >                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>            <intent-filter . . . >                <action android:name="com.example.project.BOUNCE" />                <data android:mimeType="image/jpeg" />                <category android:name="android.intent.category.DEFAULT" />            </intent-filter>        </activity>        . . .    </application></manifest> • The first filter — the combination of the action "android.intent.action.MAIN" and the category "android.intent.category.LAUNCHER" — marks the activity as one that should be represented in the application launcher, the screen listing applications users can launch on the device. • The activity is the entry point for the application, the initial one users would see when they choose the application in the launcher.

  37. Intent Filters in a Manifest <?xml version="1.0" encoding="utf-8"?><manifest . . . >    <application . . . >        <activity android:name="com.example.project.FreneticActivity"android:icon="@drawable/small_pic.png"android:label="@string/freneticLabel"                   . . .  >            <intent-filter . . . >                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>            <intent-filter . . . >                <action android:name="com.example.project.BOUNCE" />                <data android:mimeType="image/jpeg" />                <category android:name="android.intent.category.DEFAULT" />            </intent-filter>        </activity>        . . .    </application></manifest> • The second filter declares an action that the activity can perform on a particular type of data. • A component can have any number of intent filters, each one declaring a different set of capabilities. If it doesn't have any filters, it can be activated only by intents that explicitly name the component as the target. • For a broadcast receiver that's created and registered in code, the intent filter is instantiated directly as an IntentFilter object. All other filters are set up in the manifest.

  38. Intent Filters in a Manifest <?xml version="1.0" encoding="utf-8"?><manifest . . . >    <application . . . >        <activity android:name="com.example.project.FreneticActivity"android:icon="@drawable/small_pic.png"android:label="@string/freneticLabel"                   . . .  >            <intent-filter . . . >                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>            <intent-filter . . . >                <action android:name="com.example.project.BOUNCE" />                <data android:mimeType="image/jpeg" />                <category android:name="android.intent.category.DEFAULT" />            </intent-filter>        </activity>        . . .    </application></manifest> • The second filter declares an action that the activity can perform on a particular type of data. • A component can have any number of intent filters, each one declaring a different set of capabilities. If it doesn't have any filters, it can be activated only by intents that explicitly name the component as the target. • For a broadcast receiver that's created and registered in code, the intent filter is instantiated directly as an IntentFilter object. All other filters are set up in the manifest.

  39. Activities and Tasks • One activity can start another, including one defined in a different application. • Your activity can build an Intent object with the required information and pass it to startActivity() (say a map viewer) in a different application. The map viewer will display the map. When the user hits the BACK key, your activity will reappear on screen. • Users are unaware that the activities are in different applications. • Android maintains this user experience by keeping both activities in the same task.

  40. Activities and Tasks • A task is a group of related activities, arranged in a stack. The root activity in the stack is the one that began the task — typically, it's an activity the user selected in the application launcher. • The activity at the top of the stack is one that's currently running — the one that is the focus for user actions. When one activity starts another, the new activity is pushed on the stack; it becomes the running activity. The previous activity remains in the stack. When the user presses the BACK key, the current activity is popped from the stack, and the previous one resumes as the running activity.

  41. Activities and Tasks • The stack contains objects, so if a task has more than one instance of the same Activity subclass open — multiple map viewers, for example — the stack has a separate entry for each instance. Activities in the stack are never rearranged, only pushed and popped. • A task is a stack of activities, not a class or an element in the manifest file. So there's no way to set values for a task independently of its activities. • Values for the task as a whole are set in the root activity.

  42. Activities and Tasks • All the activities in a task move together as a unit. The entire task (the entire activity stack) can be brought to the foreground or sent to the background. • Senario: • The current task has four activities in its stack — three under the current activity. • The user presses the HOME key, goes to the application launcher, and selects a new application (actually, a new task). • The current task goes into the background and the root activity for the new task is displayed. Then, after a short period, the user goes back to the home screen and again selects the previous application (the previous task). • That task, with all four activities in the stack, comes forward. When the user presses the BACK key, the screen does not display the activity the user just left (the root activity of the previous task). Rather, the activity on the top of the stack is removed and the previous activity in the same task is displayed. • The behavior just described is the default behavior for activities and tasks. But there are ways to modify almost all aspects of it. The association of activities with tasks, and the behavior of an activity within a task, is controlled by the interaction between flags set in the Intent object that started the activity and attributes set in the activity's <activity> element in the manifest. Both requester and respondent have a say in what happens.

  43. Intent Flags The principal Intent flags are: • FLAG_ACTIVITY_NEW_TASK • FLAG_ACTIVITY_CLEAR_TOP • FLAG_ACTIVITY_RESET_TASK_IF_NEEDED • FLAG_ACTIVITY_SINGLE_TOP The principal <activity> attributes are: • taskAffinity • launchMode • allowTaskReparenting • clearTaskOnLaunch • alwaysRetainTaskState • finishOnTaskLaunch

  44. Affinities and New Tasks • By default, all the activities in an application have an affinity for each other — that is, there's a preference for them all to belong to the same task. • An individual affinity can be set for each activity with the taskAffinity attribute of the <activity> element. • Activities defined in different applications can share an affinity, or activities defined in the same application can be assigned different affinities. • The affinity comes into play in two circumstances: • When the Intent object that launches an activity contains the FLAG_ACTIVITY_NEW_TASK flag, • When an activity has its allowTaskReparenting attribute set to "true".

  45. FLAG_ACTIVITY_NEW_TASK • A new activity is, by default, launched into the task of the activity that called startActivity(). It's pushed onto the same stack as the caller. • If the Intent object passed to startActivity() contains the FLAG_ACTIVITY_NEW_TASK flag, the system looks for a different task to house the new activity. Often, as the name of the flag implies, it's a new task. However, it doesn't have to be. • If there's already an existing task with the same affinity as the new activity, the activity is launched into that task. If not, it begins a new task.

  46. allowTaskReparenting Attribute • If an activity has its allowTaskReparenting attribute set to "true", it can move from the task it starts in to the task it has an affinity for when that task comes to the fore. • Scenario: • An activity that reports weather conditions in selected cities is defined as part of a travel application. It has the same affinity as other activities in the same application (the default affinity) and it allows reparenting. • One of your activities starts the weather reporter, so it initially belongs to the same task as your activity. However, when the travel application next comes forward, the weather reporter will be reassigned to and displayed with that task. • If an .apk file contains more than one "application" from the user's point of view, you will probably want to assign different affinities to the activities associated with each of them.

  47. Launch modes • There are four different launch modes that can be assigned to an <activity> element's launchMode attribute: 1) "standard" (the default mode) 2) "singleTop" 3) "singleTask" 4) "singleInstance"

  48. Launch modes The modes differ from each other on these four points: • Which task will hold the activity that responds to the intent. For the "standard" and "singleTop" modes, it's the task that originated the intent (and called startActivity()) — unless the Intent object contains the FLAG_ACTIVITY_NEW_TASK flag. In that case, a different task is chosen. In contrast, the "singleTask" and "singleInstance" modes mark activities that are always at the root of a task. They define a task; they're never launched into another task. • Whether there can be multiple instances of the activity. A "standard" or "singleTop" activity can be instantiated many times. They can belong to multiple tasks, and a given task can have multiple instances of the same activity. In contrast, "singleTask" and "singleInstance" activities are limited to just one instance. Since these activities are at the root of a task, this limitation means that there is never more than a single instance of the task on the device at one time.

  49. Launch modes • Whether the instance can have other activities in its task. A "singleInstance" activity stands alone as the only activity in its task. If it starts another activity, that activity will be launched into a different task regardless of its launch mode — as if FLAG_ACTIVITY_NEW_TASK was in the intent. In all other respects, the "singleInstance" mode is identical to "singleTask". The other three modes permit multiple activities to belong to the task. A "singleTask" activity will always be the root activity of the task, but it can start other activities that will be assigned to its task. Instances of "standard" and "singleTop" activities can appear anywhere in a stack.

  50. Launch modes • Whether a new instance of the class will be launched to handle a new intent. For the default "standard" mode, a new instance is created to respond to every new intent. Each instance handles just one intent. For the "singleTop" mode, an existing instance of the class is re-used to handle a new intent if it resides at the top of the activity stack of the target task. If it does not reside at the top, it is not re-used. Instead, a new instance is created for the new intent and pushed on the stack. • For example, suppose a task's activity stack consists of root activity A with activities B, C, and D on top in that order, so the stack is A-B-C-D. An intent arrives for an activity of type D. If D has the default "standard" launch mode, a new instance of the class is launched and the stack becomes A-B-C-D-D. However, if D's launch mode is "singleTop", the existing instance is expected to handle the new intent (since it's at the top of the stack) and the stack remains A-B-C-D. • If, on the other hand, the arriving intent is for an activity of type B, a new instance of B would be launched no matter whether B's mode is "standard" or "singleTop" (since B is not at the top of the stack), so the resulting stack would be A-B-C-D-B.

More Related