Android applications are composed of one or more application components (activities, services, content providers, and broadcast receivers)
Each component performs a different role in the overall application behavior, and each one can be activated individually (even by other applications)
The manifest file must declare all components in the application and should also declare all application requirements, such as the minimum version of Android required and any hardware configurations required
Non-code application resources (images, strings, layout files, etc.) should include alternatives for different device configurations (such as different strings for different languages and different layouts for different screen sizes)
Androidapplications are written in the Java programming language. The Android SDKtools compile the code—along with any data and resource files—into an Android package, an archive file with an .apk suffix. Allthe code in a single .apk file is considered to be one application and is thefile that Android-powered devices use to install the application.
Onceinstalled on a device, each Android application lives in its own securitysandbox:
The Android operating system is a multi-user Linux system in which each application is a different user.
By default, the system assigns each application a unique Linux user ID (the ID is used only by the system and is unknown to the application). The system sets permissions for all the files in an application so that only the user ID assigned to that application can access them.
默认情况下，系统会给每一个APP分配一个唯一的Linux UID(这个ID只能被系统使用而相对于APP之间是不会知道的，这样他们就不能互访对方的文件，因为他们根本不知道或者无法获得对方APP的Linux UID。这样，相对于每一个APP来说是安全的了). 系统会为APP的所有文件设置权限以便只有被分配Linux UID的才能访问它们
Each process has its own virtual machine (VM), so an application's code runs in isolation from other applications.
By default, every application runs in its own Linux process. Android starts the process when any of the application's components need to be executed, then shuts down the process when it's no longer needed or when the system must recover memory for other applications.
Inthis way, the Android system implements the principle of least privilege. Thatis, each application, by default, has access onlyto the components that it requires to do its work and no more.This creates a very secure environment in which an application cannot accessparts of the system for which it is not given permission.
通过这种方式，Android系统实现了 “最少特权原则”. 也就是每一个APP在默认情况下，只能访问在工作中请求的组件而不能再访问其他的了. 这样就为APP不能访问系统未授权的组件而创造了一个非常安全的环境.
Android系统利用了两个机制来保证APP之间的安全：1.Linux UID 访问权限控制 机制，即只有拥有该LinuxUID的才能访问，而每个APP只有唯一的一个LinuxUID；2.DVM隔离机制，即一个APP只运行在一个单独的DVM进程上，任何一个APP都不和其他APP共享DVM进程，从而防止了多个APP在同一个DVM进程上会共享内存而引发的不安全因素。 而从另一个角度看到的一个有利因素是：当一个DVM进程在系统上死掉的时候不会导致所有APP都死掉，这样就防止了系统死机，系统重启的情况发生，从而提高了系统运行质量，系统的用户体验
However,there are ways for an application to share data with other applications and foran application to access system services:
It's possible to arrange for two applications to share the same Linux user ID, in which case they are able to access each other's files. To conserve system resources, applications with the same user ID can also arrange to run in the same Linux process and share the same VM (the applications must also be signed with the same certificate).
当两个APP想要访问对方文件时，系统可以为两个APP安排相同的Linux UID. 为了共享系统资源，拥有相同Linux UID的APP可以被安排到同一个Linux进程来共享同一个DVM(必须是拥有相同签名的APP，也就是不能访问他人开发的APP，同一个人开发的APP可以互相访问)
An application can request permission to access device data such as the user's contacts, SMS messages, the mountable storage (SD card), camera, Bluetooth, and more. All application permissions must be granted by the user at install time.
Thatcovers the basics regarding how an Android application exists within thesystem. The rest of this document introduces you to:
The core framework components that define your application.
The manifest file in which you declare components and required device features for your application.
Resources that are separate from the application code and allow your application to gracefully optimize its behavior for a variety of device configurations.
Applicationcomponents are the essential building blocks ofan Android application. Each component is a different pointthrough which the system can enter yourapplication. Not all components are actual entrypoints for the user and some depend on each other, but each oneexists as its own entity and plays a specific role—each one is a unique building block that helps define yourapplication's overall behavior.
Thereare four different types of application components. Each type serves a distinctpurpose and has a distinct lifecycle that defines how the component is createdand destroyed.
Hereare the four types of application components:
An activity represents a single screen with auser interface. For example, an email application might have one activity thatshows a list of new emails, another activity to compose an email, and anotheractivity for reading emails. Although the activities work together to forma cohesive(紧密结合的) userexperience in the email application, each one is independent of the others. Assuch, a different application can start any one of these activities (ifthe email application allows it). For example, a camera application can startthe activity in the email application that composes new mail, in order for theuser to share a picture.
A service is a component that runs in thebackground to perform long-running operations or to perform work for remote processes. A service does not provide a user interface. For example, aservice might play music in the background while the user is in a differentapplication, or it might fetch data over the network without blocking userinteraction with an activity. Another component, such as an activity, can start the service and let it run or bind to it in order to interact with it.
A content provider manages a shared set ofapplication data. You can store the data in the filesystem, an SQLite database, on the web, or anyother persistent storage location your application canaccess. Through the content provider, other applications can query or evenmodify the data (if the content provider allows it). For example, the Androidsystem provides a content provider that manages the user's contact information.As such, any application with the proper permissions can query part of thecontent provider (such as
ContactsContract.Data) to readand write information about a particular person.
Contentproviders are also useful for reading and writing data that is private to yourapplication and not shared. For example, the Note Pad sampleapplication uses a content provider to save notes.
Acontent provider is implemented as a subclass of
ContentProvider andmust implement a standard set of APIs that enable other applications to performtransactions. For more information, see the Content Providers developerguide.
A broadcast receiver is a component that responds to system-wide broadcast announcements. Many broadcasts originate（发起） fromthe system—for example, a broadcast announcing(宣告)thatthe screen has turned off, the battery is low, or a picture was captured.Applications can also initiate(发起) broadcasts—forexample, to let other applications know that some data has been downloaded tothe device and is available for them to use. Althoughbroadcast receivers don't display a user interface,they may create a status bar notification toalert the user when a broadcast event occurs. Morecommonly, though, a broadcast receiver is just a"gateway" to other components and is intended to do a very minimalamount of work. For instance, it might initiate a service to perform some workbased on the event.
一个 broadcast receiver 只是一个通向其他组件的“网关”，本就是打算做一些非常少量的工作
Aunique aspect of the Android system design is that anyapplication can start another application’s component. Forexample, if you want the user to capture a photo with the device camera, there'sprobably another application that does that and your application can use it,instead of developing an activity to capture a photo yourself.You don't need to incorporate or even link to the code from the cameraapplication. Instead, you can simply start the activity in the cameraapplication that captures a photo. When complete, the photo is even returned toyour application so you can use it. To the user, it seems as if the camera isactually a part of your application.
Android系统被设计的一个比较独特的方面就是：任何APP都可以启动其他APP的组件. 例如，如果你想让用户使用照相机设备去捕捉一个照片时，可能已经有其他的APP已经可以做到了，而你的APP就可以直接使用它， 而不用自己去开发一个Activity来实现照片的捕捉了. 你并不需要和照相机APP进行合并或者接入到对方的代码里. 取而代之的是，你可以很简单的去启动一个照相机APP的Activity来捕捉照片. 当完成了这个过程，这张照片就会被返回到你的APP里并且可以使用了. 对于用户来说，照相机就好像是你APP里的一部分一样.
Whenthe system starts a component, it starts the process for that application (ifit's not already running) and instantiates the classes needed for thecomponent. For example, if your application starts the activity in the cameraapplication that captures a photo, that activity runs in the process thatbelongs to the camera application, not in your application's process.Therefore, unlike applications on most other systems, Androidapplications don't have a single entry point (there'sno
main() function,for example).
当系统要启动一个APP的组件时，系统会为这个APP启动一个进程(如果它此时不是运行状态)并且立即实例化该组件的类. 例如，如果你的APP启动一个照相机APP的Activity来捕捉一张照片时，这个Activity就会运行在照相机APP进程里，而非在你的APP进程中. 所以，不同于其他系统的APP，Android APP并非只有一个单独的入口
Becausethe system runs each application in a separate process with file permissionsthat restrict access to other applications, yourapplication cannot directly activate a component from another application. TheAndroid system, however, can. So, to activate acomponent in another application, you must delivera message to the system that specifies your intent to start a particularcomponent. The system then activates the componentfor you.
因为系统运行的每个APP都是在单独的、带有文件权限的进程里，这样就限制了一个APP会进入其他APP，而不能直接激活其他APP的组件了. 但是Android系统可以. 所以，如果你要激活其他APP里的组件，你必须向系统提交一个指定你意图的消息来启动指定的组件. 系统会为你激活该组件.
Threeof the four component types—activities, services, and broadcastreceivers—are activated by an asynchronousmessage called an intent. Intents bind individualcomponents to each other at runtime (you can think of them as the messengersthat request an action from other components), whether the component belongs toyour application or another.
使用异步消息intent可以激活activities, services, broadcastreceivers这三个组件，无论这个组件是否属于你的APP你都可以在运行时单独的互相绑定(你可以认为他们就像一些从其他组件请求一个动作的信息)
Anintent is created with an
Intent object,which defines a message to activate either a specific component or aspecific type ofcomponent—an intent can be either explicitor implicit(显式或隐式的), respectively.
Foractivities and services, an intent defines the action to perform (for example,to "view" or "send" something) and mayspecify the URI of the data to act on (among other thingsthat the component being started might need to know). For example, an intentmight convey(传达) a requestfor an activity to show an image or to open a web page. In some cases, youcan start an activity to receive a result, in whichcase, the activity also returns the result in an
Intent (forexample, you can issue an intent to let the user pick a personal contact andhave it returned to you—the return intent includes a URI pointingto the chosen contact).
Forbroadcast receivers, the intent simply defines the announcement being broadcast (forexample, a broadcast to indicate thedevice battery is low includes only a known action string that indicates"battery is low").
Theother component type, content provider, is not activated byintents. Rather, it is activated when targeted by arequest from a
ContentResolver.The content resolver handles all direct transactions with the content providerso that the component that's performing transactions with the provider doesn'tneed to and instead calls methods on the
ContentResolver object.This leaves a layer of abstraction between the content provider and thecomponent requesting information (for security).
ContentProvider不能被intent激活.当然了，当Content Provider被作为Content Resolver选定的请求目标就可以被激活了. Content Resolver可以处理组件与Content Provider的全部直接交互，以便该组件不需要跟调用Content Provider的方法而调用Content Resolver对象的方法代替即可.可以看出，Content Resolver存活在一个请求信息的组件与Content provider之间的抽象层
Thereare separate methods for activating each type of component:
Beforethe Android system can start an application component, the system must knowthat the component exists by reading the application's
AndroidManifest.xml file(the "manifest" file). Your application must declare all itscomponents in this file, which must be at the root of the application projectdirectory.
Themanifest does a number of things in addition to declaringthe application's components, such as:
Identify any user permissions the application requires, such as Internet access or read-access to the user's contacts.
Declare the minimum API Level required by the application, based on which APIs the application uses.
Declare hardware and software features used or required by the application, such as a camera, bluetooth services, or a multitouch screen.
API libraries the application needs to be linked against (other than the Android framework APIs), such as the Google Maps library.
Theprimary task of the manifest is to inform thesystem about the application's components. For example, a manifest file candeclare an activity as follows:
<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
<application android:icon="@drawable/app_icon.png" ... >
android:label="@string/example_label" ... >
android:icon attributepoints to resources for an icon that identifies the application.
android:name attributespecifies the fully qualified class name ofthe
Activity subclass andthe
android:labelattributesspecifies a string to use as the user-visible label for the activity.
Youmust declare all application components this way:
<activity>elements for activities
<service>elements for services
<receiver>elements for broadcast receivers
<provider>elements for content providers
Activities,services, and content providers that you include in your source but do notdeclare in the manifest are not visible to the system and,consequently, can never run. However, broadcast receivers can be eitherdeclared in the manifest or created dynamically in code (as
BroadcastReceiver objects)and registered with the system by calling
Activities,services, and content providers在你的源代码中包含，但没有在manifest文件中声明，对于系统来说是不可见的，同时，永远不能被运行。但是broadcast receivers可以在manifest文件中声明，也可以再代码里动态的创建并且调用registerReceiver()方法向系统注册。
Formore about how to structure the manifest file for your application, seethe The AndroidManifest.xml File documentation.
Asdiscussed above, in Activating Components,you can use an
Intent tostart activities, services, and broadcast receivers. You can do so byexplicitly naming the target component (using the component class name) in theintent. However, the real power ofintents lies in the concept of intent actions. With intentactions, you simply describe the type of action youwant to perform (and optionally, the data upon which you’d like to perform the action) and allow the system to find acomponent on the device that can perform the action and start it. If there aremultiple components that can perform the action described by the intent, thenthe user selects which one to use.
Theway the system identifies the components that can respond to an intent is bycomparing the intent received to the intent filters provided in themanifest file of other applications on the device.
Whenyou declare anactivity in your app's manifest, you can optionally includeintent filters thatdeclare the capabilities of the activity so it can respondto intents fromother apps. You can declare an intentfilter for your component byadding an <intent-filter> elementasa child of the component's declaration element.
Forexample, ifyou've built an email app with an activity for composing a newemail, you candeclare an intent filter to respond to "send" intents(in order tosend a new email) like this:
<manifest ... >
<application ... >
<action android:name="android.intent.action.SEND" />
<data android:type="*/*" />
<category android:name="android.intent.category.DEFAULT" />
Formore about creating intent filters, see the Intents and Intent Filters document.
There are avariety of devices powered by Android and not all of them provide the samefeatures and capabilities. In order to prevent your app from being installed ondevices that lack features needed by your app, it's important that you clearlydefine a profile for the types of devices your app supports by declaring deviceand software requirements in your manifest file. Most of thesedeclarations are informational only and the system does not read them, but externalservices such as Google Play do read them in order to provide filtering forusers when they search for apps from their device.
For example, ifyour app requires a camera and uses APIs introduced in Android 2.1 (API Level 7), you should declare these asrequirements in your manifest file like this:
<manifest ... >
<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="19" />
Now, devicesthat do not have a camera and have an Android version lower than2.1 cannot install your app from Google Play.
However, you canalso declare that your app uses the camera, but does not require it.In that case, your app must set the required attribute to "false" and check atruntime whether the device has a camera and disable any camera features asappropriate.
More informationabout how you can manage your app's compatibility with different devices isprovided in theDevice Compatibility document.
An Android appis composed of more than just code—it requires resources that are separate fromthe source code, such as images, audio files, and anything relating to thevisual presentation of the app. For example, you should define animations,menus, styles, colors, and the layout of activity user interfaces with XMLfiles. Using app resources makes it easy to update various characteristics ofyour app without modifying code and—by providing sets of alternativeresources—enables you to optimize your app for a variety of deviceconfigurations (such as different languages and screen sizes).
For every resourcethat you include in your Android project, the SDK build tools define a uniqueinteger ID, which you can use to reference the resource from yourapp code or from other resources defined in XML. For example, if your appcontains an image file named logo.png (saved in the res/drawable/ directory),the SDK tools generate a resource ID named R.drawable.logo, which you canuse to reference the image and insert it in your user interface.
One of the mostimportant aspects of providing resources separate from your source code is the ability for youto provide alternative resources for different device configurations. For example,by defining UI strings in XML, you can translate the strings into otherlanguages and save those strings in separate files. Then, based on a language qualifier thatyou append to the resource directory's name (such as res/values-fr/ for Frenchstring values) and the user's language setting, the Android system applies theappropriate language strings to your UI.
Android supportsmany different qualifiers for your alternative resources. Thequalifier is a short string that you include in the name of your resourcedirectories in order to define the device configuration for which thoseresources should be used. As another example, you should often create differentlayouts for your activities, depending on the device's screen orientation and size.For example, when the device screen is in portrait orientation (tall), youmight want a layout with buttons to be vertical, but when the screen is inlandscape orientation (wide), the buttons should be aligned horizontally. Tochange the layout depending on the orientation, you can define two differentlayouts and apply the appropriate qualifier to each layout's directory name.Then, the system automatically applies the appropriate layout depending on thecurrent device orientation.
For more aboutthe different kinds of resources you can include in your application and how tocreate alternative resources for different device configurations, read Providing Resources.