文档章节

[Android官方API阅读]___<Application Fundamentals>

Endroid
 Endroid
发布于 2014/02/26 22:25
字数 5123
阅读 164
收藏 0

学Android不少时间了,项目做的比较少,虽然没找到Android相关的工作,但我仍然不会放弃对Android继续研究的坚持。

准备就看官方文档在抓基础,继续吸收官方的观点跟重点,希望自己能坚持下去

以下的官方文档阅读,会贴出原文,会有一下几个点:

1.读到觉得是重点或者又一次深入理解到的地方会用红色标注

2.觉得需要用中文表达一下的地方下面会跟翻译,其中翻译中也会加入自己的看法

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)

    每一个组件都可以被自己甚至其他应用程序单独的调用

  • 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:

一旦被安装在设备上,那么每一个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只有唯一的一个LinuxUID2.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.

Application Components

Applicationcomponents are the essential building blocks ofan Android application. Each component is a different pointthrough which the system can enter yourapplicationNot 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

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

content provider manages a shared set ofapplication data. You can store the data in the filesysteman SQLite databaseon the webor 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

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 applicationyou 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里的组件,你必须向系统提交一个指定你意图的消息来启动指定的组件. 系统会为你激活该组件.

 

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你都可以在运行时单独的互相绑定(你可以认为他们就像一些从其他组件请求一个动作的信息)

 

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:

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:

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.

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就可以轻松地描述相互来,而且允许系统去设备上找寻能够支持这类动作的组件并且启动它。如果有多个组件支持这类的动作,就会让用户去选择一种。

 

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.

 

当你在appmanifest文件里声明一个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 thembut 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.


© 著作权归作者所有

Endroid
粉丝 8
博文 46
码字总数 68781
作品 0
深圳
程序员
私信 提问
Android 程序测试简介

Testing 译者署名:CodingMyWorld 译者博客:http://www.cnblogs.com/codingmyworld/ 版本:Android 3.2 r1 原文 http://developer.android.com/guide/topics/testing/index.html 测试 Andr......

阿酷
2011/11/17
837
0
[雪峰磁针石博客]kotlin书籍汇总

下载地址 Learning Kotlin by Building Android Applications - 2018 初级 Develop amazing applications that will help you understand and explore the fundamentals of Kotlin while co......

python测试开发人工智能安全
2018/08/30
0
0
Dev Guide_Android Basics_Application Fundamenta

(0) Application Fundamentals Android applications are written in the Java programming language. The Android SDK tools compile the code—along with any data and resource files—i......

丁天又
2011/10/14
0
0
Android InstrumentationTestRunner 链接整理(白盒测试)

InstrumentationTestRunner(API):http://developer.android.com/reference/android/test/InstrumentationTestRunner.html Activity Testing Tutorial:http://developer.android.com/tool......

智能小松鼠
2014/12/16
0
0
android开发基础(Android Application Fundamentals)

应用基础 在Java编程语言编写的Android应用程序的Android的SDK工具编译代码以及与任何数据和到一个Android的包,一个归档文件档案资源的后缀,所有的在一个单一的代码文件被认为是一个应用程...

_kxng
2011/08/03
0
3

没有更多内容

加载失败,请刷新页面

加载更多

rsync工具常用选项以及同步的两种方式

rsync -av /etc/passwd /tmp/1.txt #rsync的本机传输写法 rsync -av /tmp/1.txt 192.168.188.128:/tmp/2.txt #rsync的远程传输rsync格式rsync [OPTION] … SRC ......

林怡丰
今天
3
0
GatewayWorker 报错:stream_socket_server(): unable to connect to tcp://0.0.0.0:1238

GatewayWorker 报错:stream_socket_server(): unable to connect to tcp://0.0.0.0:1238 (Address already in use) 官方文档虽然有相同的问题,但是对我的问题没起作用…… 后面发现自己手贱...

wenzhizhong
昨天
2
0
REST接口

文章来源 https://zhuanlan.zhihu.com/p/28674721?group_id=886181549958119424 http://www.ruanyifeng.com/blog/2014/05/restful_api.html REST 对请求的约定 REST 用来规范应用如何在 HTTP......

Airship
昨天
5
0
Spring Cloud Config 统一配置中心

Spring Cloud Config 统一配置中心 一、统一配置中心 统一管理配置 通常,我们会使用配置文件来管理应用的配置。如一个 Spring Boot 的应用,可以将配置信息放在 application.yml 文件中,如...

非摩尔根
昨天
6
0
android ------ AAPT2 error: check logs for details解决方法

AAPT 是全称是 Android Asset Packaging Tool,它是构建 App,甚至是构建 Android 系统都必不可少的一个工具。它的作用是将所有资源文件压缩打包到Android APK 当中。我们在 Android SDK 目录...

切切歆语
昨天
3
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部