[Android官方API阅读]___Application Fundamentals
2019獨角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
學(xué)Android不少時間了,項目做的比較少,雖然沒找到Android相關(guān)的工作,但我仍然不會放棄對Android繼續(xù)研究的堅持。
準(zhǔn)備就看官方文檔在抓基礎(chǔ),繼續(xù)吸收官方的觀點跟重點,希望自己能堅持下去
以下的官方文檔閱讀,會貼出原文,會有一下幾個點:
1.讀到覺得是重點或者又一次深入理解到的地方會用紅色標(biāo)注
2.覺得需要用中文表達(dá)一下的地方下面會跟翻譯,其中翻譯中也會加入自己的看法
Application Fundamentals
Quickview
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)
?? ?每一個組件都可以被自己甚至其他應(yīng)用程序單獨的調(diào)用
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:
一旦被安裝在設(shè)備上,那么每一個Android APP都存活在自己的安全沙盒中
The Android operating system is a multi-user Linux system in which each application is a different user.
Android系統(tǒng)是一個多用戶的Linux系統(tǒng),其中每一個應(yīng)用程序是一個不同的用戶?
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.
默認(rèn)情況下,系統(tǒng)會給每一個APP分配一個唯一的Linux UID(這個ID只能被系統(tǒng)使用而相對于APP之間是不會知道的,這樣他們就不能互訪對方的文件,因為他們根本不知道或者無法獲得對方APP的Linux UID。這樣,相對于每一個APP來說是安全的了).?系統(tǒng)會為APP的所有文件設(shè)置權(quán)限以便只有被分配Linux UID的才能訪問它們
Each process has its own virtual machine (VM), so an application's code runs in?isolation?from other applications.
每一個進(jìn)程會有自己單獨的虛擬機,所以一個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.
默認(rèn)情況下,每一個APP會運行在自己的Linux進(jìn)程中.當(dāng)一個APP的任何一個組將需要被執(zhí)行時,Android系統(tǒng)會來啟動這個進(jìn)程;而當(dāng)不在需要時Android系統(tǒng)將會關(guān)閉這個進(jìn)程或者系統(tǒng)為了其他APP的正常運行而必須回收當(dāng)前APP使用的內(nèi)存
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系統(tǒng)實現(xiàn)了?“最少特權(quán)原則”.?也就是每一個APP在默認(rèn)情況下,只能訪問在工作中請求的組件而不能再訪問其他的了.?這樣就為APP不能訪問系統(tǒng)未授權(quán)的組件而創(chuàng)造了一個非常安全的環(huán)境.
?
總結(jié):
Android系統(tǒng)利用了兩個機制來保證APP之間的安全:1.Linux UID?訪問權(quán)限控制?機制,即只有擁有該LinuxUID的才能訪問,而每個APP只有唯一的一個LinuxUID;2.DVM隔離機制,即一個APP只運行在一個單獨的DVM進(jìn)程上,任何一個APP都不和其他APP共享DVM進(jìn)程,從而防止了多個APP在同一個DVM進(jìn)程上會共享內(nèi)存而引發(fā)的不安全因素。?而從另一個角度看到的一個有利因素是:當(dāng)一個DVM進(jìn)程在系統(tǒng)上死掉的時候不會導(dǎo)致所有APP都死掉,這樣就防止了系統(tǒng)死機,系統(tǒng)重啟的情況發(fā)生,從而提高了系統(tǒng)運行質(zhì)量,系統(tǒng)的用戶體驗
在開發(fā)中這兩個機制使得我們會做以下的操作:1.對于第一個機制:訪問系統(tǒng)其他的APP組件時必須在manifest文件中向系統(tǒng)申請權(quán)限或注冊權(quán)限,在安裝時向用戶展示該APP需要訪問的權(quán)限,由用戶對于某一權(quán)限是否敏感而選擇是否安裝;2.對于第二個機制:APP如果要訪問系統(tǒng)Service進(jìn)程或者其他APP進(jìn)程時必須要通過IPC機制(Binder機制)來跨進(jìn)程訪問
?
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).
當(dāng)兩個APP想要訪問對方文件時,系統(tǒng)可以為兩個APP安排相同的Linux UID.?為了共享系統(tǒng)資源,擁有相同Linux UID的APP可以被安排到同一個Linux進(jìn)程來共享同一個DVM(必須是擁有相同簽名的APP,也就是不能訪問他人開發(fā)的APP,同一個人開發(fā)的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要訪問設(shè)備文件如用戶的通訊錄、短信、掛載存儲空間(SD卡)、相機、藍(lán)牙、或者更多其它,則必須向系統(tǒng)請求相應(yīng)的權(quán)限.?所有的APP權(quán)限必須在用戶安裝的時候來授予.
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.
Application Components
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(緊密結(jié)合的)?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(發(fā)起)?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(發(fā)起)?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?只是一個通向其他組件的“網(wǎng)關(guān)”,本就是打算做一些非常少量的工作
?
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系統(tǒng)被設(shè)計的一個比較獨特的方面就是:任何APP都可以啟動其他APP的組件.?例如,如果你想讓用戶使用照相機設(shè)備去捕捉一個照片時,可能已經(jīng)有其他的APP已經(jīng)可以做到了,而你的APP就可以直接使用它, 而不用自己去開發(fā)一個Activity來實現(xiàn)照片的捕捉了.?你并不需要和照相機APP進(jìn)行合并或者接入到對方的代碼里.?取而代之的是,你可以很簡單的去啟動一個照相機APP的Activity來捕捉照片.?當(dāng)完成了這個過程,這張照片就會被返回到你的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).
?
當(dāng)系統(tǒng)要啟動一個APP的組件時,系統(tǒng)會為這個APP啟動一個進(jìn)程(如果它此時不是運行狀態(tài))并且立即實例化該組件的類.?例如,如果你的APP啟動一個照相機APP的Activity來捕捉一張照片時,這個Activity就會運行在照相機APP進(jìn)程里,而非在你的APP進(jìn)程中.?所以,不同于其他系統(tǒng)的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.
?
因為系統(tǒng)運行的每個APP都是在單獨的、帶有文件權(quán)限的進(jìn)程里,這樣就限制了一個APP會進(jìn)入其他APP,而不能直接激活其他APP的組件了.?但是Android系統(tǒng)可以.?所以,如果你要激活其他APP里的組件,你必須向系統(tǒng)提交一個指定你意圖的消息來啟動指定的組件.?系統(tǒng)會為你激活該組件.
?
ActivatingComponents
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你都可以在運行時單獨的互相綁定(你可以認(rèn)為他們就像一些從其他組件請求一個動作的信息)
?
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(傳達(dá))?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激活.當(dāng)然了,當(dāng)Content Provider被作為Content Resolver選定的請求目標(biāo)就可以被激活了. Content Resolver可以處理組件與Content Provider的全部直接交互,以便該組件不需要跟調(diào)用Content Provider的方法而調(diào)用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.
The Manifest File
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
Declaringcomponents
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: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 (asBroadcastReceiver?objects)and registered with the system by calling?registerReceiver().
?
Activities,services, and content providers在你的源代碼中包含,但沒有在manifest文件中聲明,對于系統(tǒng)來說是不可見的,同時,永遠(yuǎn)不能被運行。但是broadcast receivers可以在manifest文件中聲明,也可以再代碼里動態(tài)的創(chuàng)建并且調(diào)用registerReceiver()方法向系統(tǒng)注冊。
?
Formore about how to structure the manifest file for your application, seethe?The AndroidManifest.xml File?documentation.
Declaringcomponent capabilities
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就可以輕松地描述相互來,而且允許系統(tǒng)去設(shè)備上找尋能夠支持這類動作的組件并且啟動它。如果有多個組件支持這類的動作,就會讓用戶去選擇一種。
?
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.
?
系統(tǒng)找尋組件的方式可以通過與從intent filters提供的組件類型作對比來響應(yīng)到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.
?
當(dāng)你在app的manifest文件里聲明一個activity時,你可以選擇包含一些intentfilter來聲明該activity的一些能力,就可以來響應(yīng)其他app發(fā)來的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.
轉(zhuǎn)載于:https://my.oschina.net/yaoqinwei/blog/203431
總結(jié)
以上是生活随笔為你收集整理的[Android官方API阅读]___Application Fundamentals的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python与shell校验IP地址合法
- 下一篇: NSString字符串常用知识点