如下的官方文檔閱讀,會貼出原文,會有一下幾個點:html
1.讀到以爲是重點或者又一次深刻理解到的地方會用紅色標註android
2.以爲須要用中文表達一下的地方下面會跟翻譯,其中翻譯中也會加入本身的見解web
Android applications are composed of one or more application components (activities, services, content providers, and broadcast receivers)api
Each component performs a different role in the overall application behavior, and each one can be activated individually (even by other applications)安全
每個組件均可以被本身甚至其餘應用程序單獨的調用app
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)async
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.ide
Onceinstalled on a device, each Android application lives in its own securitysandbox:fetch
一旦被安裝在設備上,那麼每個Android APP都存活在本身的安全沙盒中
The Android operating system is a multi-user Linux system in which each application is a different user.
Android系統是一個多用戶的Linux系統,其中每個應用程序是一個不一樣的用戶?
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.
每個進程會有本身單獨的虛擬機,因此一個APP會單獨的運行在一個與其餘APP隔離的空間
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.
默認狀況下,每個APP會運行在本身的Linux進程中.當一個APP的任何一個組將須要被執行時,Android系統會來啓動這個進程;而當不在須要時Android系統將會關閉這個進程或者系統爲了其餘APP的正常運行而必須回收當前APP使用的內存
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都死掉,這樣就防止了系統死機,系統重啓的狀況發生,從而提升了系統運行質量,系統的用戶體驗
在開發中這兩個機制使得咱們會作如下的操做:1.對於第一個機制:訪問系統其餘的APP組件時必須在manifest文件中向系統申請權限或註冊權限,在安裝時向用戶展現該APP須要訪問的權限,由用戶對於某一權限是否敏感而選擇是否安裝;2.對於第二個機制:APP若是要訪問系統Service進程或者其餘APP進程時必需要經過IPC機制(Binder機制)來跨進程訪問
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.
APP要訪問設備文件如用戶的通信錄、短信、掛載存儲空間(SD卡)、相機、藍牙、或者更多其它,則必須向系統請求相應的權限. 全部的APP權限必須在用戶安裝的時候來授予.
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:
Activities
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.
Anactivity is implemented as a subclass of Activity
andyou can learn more about it in the Activities developerguide.
Services
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.
Aservice is implemented as a subclass of Service
andyou can learn more about it in the Services developerguide.
Content providers
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.
Broadcast receivers
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 只是一個通向其餘組件的「網關」,本就是打算作一些很是少許的工做
Abroadcast receiver is implemented as a subclass of BroadcastReceiver
andeach broadcast is delivered as an Intent
object.For more information, see the BroadcastReceiver
class.
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 aContentResolver
.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:
You can start an activity (or give it something new to do) by passing an Intent
to startActivity()
or startActivityForResult()
(when you want the activity to return a result).
You can start a service (or give new instructions to an ongoing service) by passing an Intent
to startService()
. Or you can bind to the service by passing an Intent
to bindService()
.
You can initiate a broadcast by passing an Intent
to methods like sendBroadcast()
, sendOrderedBroadcast()
, or sendStickyBroadcast()
.
You can perform a query to a content provider by calling query()
on a ContentResolver
.
Beforethe Android system can start an application component, the system must knowthat the component exists by reading the application'sAndroidManifest.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.
And more
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" ... >
<activity android:name="com.example.project.ExampleActivity"
android:label="@string/example_label" ... >
</activity>
...
</application>
</manifest>
Inthe <application>
element,the android:icon
attributepoints to resources for an icon that identifies the application.
Inthe <activity>
element,the android:name
attributespecifies the fully qualified class name ofthe Activity
subclass andthe android:label
attributesspecifies 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 (asBroadcastReceiver
objects)and registered with the system by calling registerReceiver()
.
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.
使用指定action的intent,你想用哪種類型的aciton就能夠輕鬆地描述相互來,並且容許系統去設備上找尋可以支持這類動做的組件而且啓動它。若是有多個組件支持這類的動做,就會讓用戶去選擇一種。
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.
系統找尋組件的方式能夠經過與從intent filters提供的組件類型做對比來響應到intent
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.
當你在app的manifest文件裏聲明一個activity時,你能夠選擇包含一些intentfilter來聲明該activity的一些能力,就能夠來響應其餘app發來的intent請求了.
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 ... >
<activity android:name="com.example.project.ComposeEmailActivity">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<data android:type="*/*" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
Then,if anotherapp creates an intent with the ACTION_SEND actionandpass it to startActivity(),the system maystart your activity so the user can draft and send an email.
Formore about creating intent filters, see the Intents and Intent Filters document.
Declaring apprequirements
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-feature android:name="android.hardware.camera.any"
android:required="true" />
<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="19" />
...
</manifest>
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.
App Resources
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.