Application Fundamentals

来源:互联网 发布:网络兼职被骗已追回 编辑:程序博客网 时间:2024/06/05 23:59

Application Fundamentals 应用程序基础

Android apps are written in the Java programming language. The Android SDK tools compile your code—along with any data and resource files—into an APK: an Android package, which is an archive file with an .apk suffix. One APK file contains all the contents of an Android app and is the file that Android-powered devices use to install the app.
安卓应用是用JAVA编程语言编写的。Android SDK 工具编译你的代码中用到的所有的数据资源文件到APK:一个以.apk为后缀的安卓包。一个APK文件包含了安卓应用的所有文件。支持安卓的设备使用APK安装应用。

Once installed on a device, each Android app lives in its own security sandbox:
一旦安装到设备上,每一个安卓应用都运行在它自己的安全沙盒里:

The Android operating system is a multi-user Linux system in which each app is a different user.
安卓操作系统是一个多用户Linux系统,每个APP都是一个不同的用户。

By default, the system assigns each app a unique Linux user ID (the ID is used only by the system and is unknown to the app). The system sets permissions for all the files in an app so that only the user ID assigned to that app can access them.
默认情况下,系统分配给每个APP唯一的Linux用户ID(ID只提供给系统使用,而对于APP ID是未知的。)系统为APP中的所有文件设置了权限,所以只有分配给用APP用户ID的文件可以被该应用访问。

Each process has its own virtual machine (VM), so an app’s code runs in isolation from other apps.
每一个进程都拥有它自己的虚拟机,所有一个APP的代码是独立于其他APP运行的。

By default, every app runs in its own Linux process. Android starts the process when any of the app’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 apps.
默认情况下,每一个APP运行在它自己的Linux进程中。安卓在任何APP的组件需要执行的时候启动进程。当进程不再被需要或者当系统必须为其他APP回收内存的时候关闭进程。

In this way, the Android system implements the principle of least privilege. That is, each app, by default, has access only to the components that it requires to do its work and no more. This creates a very secure environment in which an app cannot access parts of the system for which it is not given permission.

用这种方法,安卓系统实现了最小权限原则。也就是说,每一个应用在默认情况下只能够访问它工作所需要的内容,无它。这造就了一个非常安全的环境,当一个应用没有获得权限的时,它就不能访问对应的系统部件。

However, there are ways for an app to share data with other apps and for an app to access system services:
然而,还是有办法让一个应用去共享数据给其他应用,或者让一个应用去访问系统服务:

It’s possible to arrange for two apps to share the same Linux user ID, in which case they are able to access each other’s files. To conserve system resources, apps with the same user ID can also arrange to run in the same Linux process and share the same VM (the apps must also be signed with the same certificate).
可以安排两个应用共享同一个Linux用户ID,在这种情况下它们能够互相访问应用的文件。
An app 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 app permissions must be granted by the user at install time.
应用程序可以申请权限去访问设备数据,例如用户的通讯录,信息,SD卡,相机,蓝牙等等。所有的APP权限在应用安装时都需要经过用户同意。
That covers the basics regarding how an Android app exists within the system. The rest of this document introduces you to:
以上涵盖了关于一个安卓应用是如何在系统存在的基础。剩下的部分将向你介绍:

The core framework components that define your app.
用核心框架组件定义你的应用
The manifest file in which you declare components and required device features for your app.
用清单文件声明你的应用的组件和需要的设备特性。
Resources that are separate from the app code and allow your app to gracefully optimize its behavior for a variety of device configurations.
应用代码和资源分离,可以让你去优雅的优化应用的性能以兼容各种设备配置。
App Components
App components are the essential building blocks of an Android app. Each component is a different point through which the system can enter your app. Not all components are actual entry points for the user and some depend on each other, but each one exists as its own entity and plays a specific role—each one is a unique building block that helps define your app’s overall behavior.

There are four different types of app components. Each type serves a distinct purpose and has a distinct lifecycle that defines how the component is created and destroyed.
应用程序组件是一个应用的基本构建模块。每一个组件都是系统进入应用的不同切入点。不是所有的组件都是真实的切入点,有一些组件还要视情况而定,但是每一个存在的实体都扮演着特定的角色 ——每个唯一的构建模块都会帮助你定义你的应用的总体行为。

Here are the four types of app components:
这是四个应用组件类型:

Activities
An activity represents a single screen with a user interface. For example, an email app might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails. Although the activities work together to form a cohesive user experience in the email app, each one is independent of the others. As such, a different app can start any one of these activities (if the email app allows it). For example, a camera app can start the activity in the email app that composes new mail, in order for the user to share a picture.

An activity is implemented as a subclass of Activity and you can learn more about it in the Activities developer guide.

活动
一个活动表示用户界面的一屏。例如,一个邮件应用可能会有一个活动显示一个新邮件列表,另一个活动来排版一封邮件,或者另一个活动来阅读邮件。尽管在邮箱应用中多个活动在一起工作形成一个有凝聚力的用户体验,但其中每个都是独立于其他的。一个相机应用可以在邮件应用中启动来撰写一个新邮件,为了使用户共享一张图片。

活动是实现了Activity类的子类。

Services
A service is a component that runs in the background to perform long-running operations or to perform work for remote processes. A service does not provide a user interface. For example, a service might play music in the background while the user is in a different app, or it might fetch data over the network without blocking user interaction 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 service is implemented as a subclass of Service and you can learn more about it in the Services developer guide.
service是运行在后台去执行长时间操作或者执行远程操作的组件。服务不提供用户接口,例如,当用户使用不同的应用时service可能会在后台播放音乐,或者也有可能在不阻塞用户在Activity中的操作的情况下在网络中读取数据另一种组件,比如一个Activity,可以启动service运行或者将其绑定来与之交互。

Content providers
A content provider manages a shared set of app data. You can store the data in the file system, an SQLite database, on the web, or any other persistent storage location your app can access. Through the content provider, other apps can query or even modify the data (if the content provider allows it). For example, the Android system provides a content provider that manages the user’s contact information. As such, any app with the proper permissions can query part of the content provider (such as ContactsContract.Data) to read and write information about a particular person.

Content providers are also useful for reading and writing data that is private to your app and not shared. For example, the Note Pad sample app uses a content provider to save notes.

A content provider is implemented as a subclass of ContentProvider and must implement a standard set of APIs that enable other apps to perform transactions. For more information, see the Content Providers developer guide.

内容提供器管理了一组共享的应用数据。你可以储存数据到文件系统,SQLite数据库,网页,或者任何其他的你的应用可以访问的持久化的数据。通过内容提供器应用可以查询或甚至编辑数据(如果内容提供器允许这样)。例如,安卓系统提供了一个内容提供器它管理用户的联系人信息。同样的,任何拥有合适的权限的应用都可以查询内容提供器的部件(比如 ContactsContract.Dat)来读取或者写入特定的人的信息。

内容提供器在读写应用非共享的私有数据的时候也非常有用。例如,记事本实例应用使用内容提供器去保存笔记。

一个内容提供器是一个ContentProvider 类的子类的实现,必须实现一组标准的接口,这接口些可以允许其他应用去执行事务。

Broadcast receivers
A broadcast receiver is a component that responds to system-wide broadcast announcements. Many broadcasts originate from the system—for example, a broadcast announcing that the screen has turned off, the battery is low, or a picture was captured. Apps can also initiate broadcasts—for example, to let other apps know that some data has been downloaded to the device and is available for them to use. Although broadcast receivers don’t display a user interface, they may create a status bar notification to alert the user when a broadcast event occurs. More commonly, though, a broadcast receiver is just a “gateway” to other components and is intended to do a very minimal amount of work. For instance, it might initiate a service to perform some work based on the event.

A broadcast receiver is implemented as a subclass of BroadcastReceiver and each broadcast is delivered as an Intent object. For more information, see the BroadcastReceiver class.

广播接收器
广播接收器是一个相应系统范围广播公告的组件。许多广播起源自系统——例如,屏幕旋转的关闭的广播公告,低电量,或者捕获了一张图片。应用也可以发起广播——例如,让其他应用知道一些它们可用的数据下载到了设备上,尽管广播接收器不显示用户界面,但当广播事件触发它们或许会创建一个状态栏通知来提醒用户。不过,更多情况下广播接收器只是一个“网关”做很少量的工作。例如它可以启动service来执行基于事件的工作。
广播接收器是BroadcastReceiver 类的子类的实现。

A unique aspect of the Android system design is that any app can start another app’s component. For example, if you want the user to capture a photo with the device camera, there’s probably another app that does that and your app 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 camera app. Instead, you can simply start the activity in the camera app that captures a photo. When complete, the photo is even returned to your app so you can use it. To the user, it seems as if the camera is actually a part of your app.

有些独特的安卓系统设计:如何应用都可以启动其他应用的组件。例如,如果想要用户使用设备的相机获取一张照片,可能有另一个程序你可以使用它来完成,而不是自己开发一个Activity来获取照片。你不需要合并或者甚至不需从相机应用链接代码。取而代之的是你可以简单的启动相机应用中用来获取图片的Activity。当完成时,照片甚至会返回你的应用,然后你就可以使用它。这看起来就像相机是你的应用的实际的一部分。

When the system starts a component, it starts the process for that app (if it’s not already running) and instantiates the classes needed for the component. For example, if your app starts the activity in the camera app that captures a photo, that activity runs in the process that belongs to the camera app, not in your app’s process. Therefore, unlike apps on most other systems, Android apps don’t have a single entry point (there’s no main() function, for example).
当系统启动一个组件,他会为这个应用启动一个进程(如果他还未运行。)然后实例化组件需要的类。例如 如果你的应用启动相机应用的Activity来获取一张图片,这个Activity运行的进程属于相机应用而不是在你的应用的进程内。因此,不同于其他系统上的应用,安卓应用没有单一的切入点(它们没有 main()函数就是一个例子);

Because the system runs each app in a separate process with file permissions that restrict access to other apps, your app cannot directly activate a component from another app. The Android system, however, can. So, to activate a component in another app, you must deliver a message to the system that specifies your intent to start a particular component. The system then activates the component for you.

由于系统运行每一个应用于单独的进程中,文件权限也限制了应用访问其他应用,所以你的应用不能直接其他应用的组件。然而安卓系统可以。所以想要激活其他应用中的组件,你必须为系统提供指定你想要启动的组件的intent信息,系统会为你激活组件。

Activating Components

Three of the four component types—activities, services, and broadcast receivers—are activated by an asynchronous message called an intent. Intents bind individual components to each other at runtime (you can think of them as the messengers that request an action from other components), whether the component belongs to your app or another.
四种类型的组件中的三种:activity,service和broadcast receiver的激活需要一种异步消息,这种消息被称为Intent。在运行时环境下Intent将每个特点的组件绑定(你可以理解为就像一个由其他组件发起的动作请求消息。),不管组件是否属于你的应用。

An intent is created with an Intent object, which defines a message to activate either a specific component or a specific type of component—an intent can be either explicit or implicit, respectively.
一个Intent实例通过Intent对象创建,它定义了一个激活特定组件或者特定类型组件的消息。组件可以是显示的或隐式的或者respectively。

For activities and services, an intent defines the action to perform (for example, to “view” or “send” something) and may specify the URI of the data to act on (among other things that the component being started might need to know). For example, an intent might convey a request for an activity to show an image or to open a web page. In some cases, you can start an activity to receive a result, in which case, the activity also returns the result in an Intent (for example, you can issue an intent to let the user pick a personal contact and have it returned to you—the return intent includes a URI pointing to the chosen contact).
就activity和service而言,一个Intent定义了动作并执行(例如,查看或者发送一些东西),也可以指定数据的URI并执行(以及其他组件启动后需要获取的东西)。例如,一个Intent可以表示一个请求,让一个activity去显示一张图片或者大可一个web页面。在某些情况下,你可以启动activity然后接受一个返回内容。还有些情况,activity也可以返回内容通过Intent(例如,你可以发出一个Intent让用户选择一个联系人然后返回给你,这个返回的Intent就包括了一个联系人的RUI。)

For broadcast receivers, the intent simply defines the announcement being broadcast (for example, a broadcast to indicate the device battery is low includes only a known action string that indicates “battery is low”).
就broadcast receiver而言,Intent 简单的定义了通知开始广播(例如,一个低电量指示广播只包含一个已知的操作字符串“低电量”)。

The other component type, content provider, is not activated by intents. Rather, it is activated when targeted by a request from a ContentResolver. The content resolver handles all direct transactions with the content provider so that the component that’s performing transactions with the provider doesn’t need to and instead calls methods on the ContentResolver object. This leaves a layer of abstraction between the content provider and the component requesting information (for security).
其他的组件类型:content provider不是通过Intent激活的,它是当被一个ContentResolver定向时激活。 Content Resolver操控了所用的content provider事务管理,所以这种控件自身不需要去执行事务,而是要调用Content Resolver 的方法。Content Resolver 是一个在content provider和组件请求信息之间的抽象层(为了安全考虑)。

There are 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.
你可以通过传递一个Intent参数给startActivity()或者startActivityForResult() (当你想要activity返回一个结果)启动一个activity(或者是传递些新的东西给它)。
你可以启动service(或者传递指令给正在运行的service)通过传递一个Intent参数给startService(). 或者你可以绑定服务通过传递Intent参数给 bindService().
你可以通过传递一个Intent参数到就像sendBroadcast(),sendOrderedBroadcast()或者sendStickyBroadcast()的方法来发送一个广播。
你可以对通过调用ContentResolver的query()方法来对content provider进行查询。

For more information about using intents, see the Intents and Intent Filters document. More information about activating specific components is also provided in the following documents: Activities, Services, BroadcastReceiver and Content Providers.
想要了解更多关于如何使用Intent的信息,请使用Intents and Intent Filters文档。

The Manifest File

The primary task of the manifest is to inform the system about the app’s components. For example, a manifest file can declare an activity as follows:
manifest 的首要任务就是告知系统APP中用了哪些组件。例如,一个manifest 文件可以声明一个activity 就像下面这样:

<?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>

In the < application> element, the android:icon attribute points to resources for an icon that identifies the app.
在 < application>元素中,android:icon属性指定了一个用于辨识app的图标资源。

In the < activity> element, the android:name attribute specifies the fully qualified class name of the Activity subclass and the android:label attributes specifies a string to use as the user-visible label for the activity.
在< activity>元素中,android:name 属性指定了Activity 子类的全路径名。android:label 属性指定了一个用于activity的用户可见标签的字符串。

You must declare all app components this way:
你必须通过以下方法声明所有的应用组件:

< activity> elements for activities
< service> elements for services
< receiver> elements for broadcast receivers
< provider> elements for content providers
< activity> 元素用于activity
< service> 元素用于service
< receiver> 元素用于broadcast receiver
< provider> 元素用于 content provider
Activities, services, and content providers that you include in your source but do not declare in the manifest are not visible to the system and, consequently, can never run. However, broadcast receivers can be either declared in the manifest or created dynamically in code (as BroadcastReceiver objects) and registered with the system by calling registerReceiver().
Activity,service和content provider 在你的代码中存在但是没有在manifest 声明将不会在系统中显示,因此也永远不能运行。然而 broadcast receiver可以在manifest 或者在代码中动态的创建(就像BroadcastReceiver 对象),通过系统调用registerReceiver()注册。

For more about how to structure the manifest file for your app, see The AndroidManifest.xml File documentation.
更多关于怎样去构造你的应用的manifest文件的信息,请查看The AndroidManifest.xml File 文档。

Declaring component capabilities
声明组件功能
As discussed above, in Activating Components, you can use an Intent to start activities, services, and broadcast receivers. You can do so by explicitly naming the target component (using the component class name) in the intent. However, the real power of intents lies in the concept of implicit intents. An implicit intent simply describes the type of action to perform (and, optionally, the data upon which you’d like to perform the action) and allows the system to find a component on the device that can perform the action and start it. If there are multiple components that can perform the action described by the intent, then the user selects which one to use.
如上所述,对于激活组件,你可以使用Intent来启动activity,service和broadcast receiver。你可以在Inten中明确的命名组件的目标(使用组件的类名)。然而,Intent真正强大的地方在于隐式Intent这个概念。一个隐式的Intent简单的描述了要执行的动作的类型(随意的,你想要执行的动作的数据),然后由系统去查找设备上可以执行这个动作的组件然后执行。

The way the system identifies the components that can respond to an intent is by comparing the intent received to the intent filters provided in the manifest file of other apps on the device.
系统识别出可以响应intent的组件,通过过滤器将接受到的Intent与的设备上其他应用的manifest 文件进行对比来实现。

When you declare an activity in your app’s manifest, you can optionally include intent filters that declare the capabilities of the activity so it can respond to intents from other apps. You can declare an intent filter for your component by adding an < intent-filter> element as a child of the component’s declaration element.
当你在应用的manifest中声明一个activity时,你可以视情况添加声明了activity功能的Intent过滤器,因此它可以响应其他应用的的Intent。你可以通过添加一个类于这样的组件声明元素的子元素:< intent-filter> 元素来声明一个Intent过滤器。

For example, if you’ve built an email app with an activity for composing a new email, you can declare an intent filter to respond to “send” intents (in order to send a new email) like this:
例如,如果你建立了一个拥用于写邮件的activity的email应用,亦可以声明一个Intent过滤器来响应“发送”Intent(用来发送一封新邮件)就像这样:

<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 another app creates an intent with the ACTION_SEND action and pass it to startActivity(), the system may start your activity so the user can draft and send an email.
接下来 如果另一个app创建了一个包含ACTION_SEND动作的Intent并传递给startActivity();系统就可以启动你的activity这样用户就可以新建并发送邮件了。
For more about creating intent filters, see the Intents and Intent Filters document.
更多关于Inten过滤器的信息请查看 Intents and Intent Filters 文档。

Declaring app requirements
申明app需求

There are a variety of devices powered by Android and not all of them provide the same features and capabilities. In order to prevent your app from being installed on devices that lack features needed by your app, it’s important that you clearly define a profile for the types of devices your app supports by declaring device and software requirements in your manifest file. Most of these declarations are informational only and the system does not read them, but external services such as Google Play do read them in order to provide filtering for users when they search for apps from their device.
有各种各样的设备由Android驱动,但他们并不都提供相同的特征和功能。为了防止你的应用安装在缺少你的App需要的特性的设备上,通过声明设备和软件需求,在manifest文件中清楚的定义一个你的app支持的设备类型的概况是非常重要的。大多数的声明只是报告性质的,系统不会读取他,但是外部服务例如google play 会读取他们用于给在其他设备上搜索你的应用的用户提供过滤。

For example, if your app requires a camera and uses APIs introduced in Android 2.1 (API Level 7), you should declare these as requirements in your manifest file like this:
例如,如果你的App需要一个相机并且要使用API引入版本是Android2.1(API Level 7),你应该声明这些要求在manifest文件中就像这样:

<manifest ... >    <uses-feature android:name="android.hardware.camera.any"                  android:required="true" />    <uses-sdk android:minSdkVersion="7" android:targetSdkVersion="19" />    ...</manifest>

Now, devices that do not have a camera and have an Android version lower than 2.1 cannot install your app from Google Play.
现在 没有相机和Android版本低于2.1的设备就不能通过Google play安装你的App了。

However, you can also 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 at runtime whether the device has a camera and disable any camera features as appropriate.
然而,你也可以声明你的应用使用相机,但是并是必需使用它。在这种情况下,你的app必须设置required 属性为“false”,当运行时检查设备是否有一个相机,然后视情况来关闭应用中所有的使用到相机的特性。

More information about how you can manage your app’s compatibility with different devices is provided in the Device Compatibility document.
更多关于怎样管理你的app在不同的设备上的兼容性的信息由Device Compatibility 文档提供。

App Resources
应用资源

An Android app is composed of more than just code—it requires resources that are separate from the source code, such as images, audio files, and anything relating to the visual presentation of the app. For example, you should define animations, menus, styles, colors, and the layout of activity user interfaces with XML files. Using app resources makes it easy to update various characteristics of your app without modifying code and—by providing sets of alternative resources—enables you to optimize your app for a variety of device configurations (such as different languages and screen sizes).
一个Android应用的组成并不只包括代码,还需要与代码分离的资源。比如图片,音频文件,和任何app的和可视化展示有关的东西。
例如,你需要定义动画,菜单,风格,颜色,和XML文件形式的activity用户界面布局。使用app资源使得更新app的各种特征变得简单,而不需要编辑代码。通过提供可替代的资源集合,你能够为各种设备配置优化你的app(比如不同的语言和屏幕尺寸)。

One of the most important aspects of providing resources separate from your source code is the ability for you to provide alternative resources for different device configurations. For example, by defining UI strings in XML, you can translate the strings into other languages and save those strings in separate files. Then, based on a language qualifier that you append to the resource directory’s name (such as res/values-fr/ for French string values) and the user’s language setting, the Android system applies the appropriate language strings to your UI.
提供与你的代码分离的资源文件,是对你去为不同的设备配置提供可替代资源的能力的一个非常重要的方面。例如在XML文件中定义UI字符串,你可以把字符串翻译成其他语言,然后保存这些字符串在一个特定的文件中。然后,根据将语言限定符添加到资源目录的名字中(例如 res/values-fr 对应着法语字符串资源)和用户的语言设置,Android系统请求对应的语言字符串显示到你的UI。

Android supports many different qualifiers for your alternative resources. The qualifier is a short string that you include in the name of your resource directories in order to define the device configuration for which those resources should be used. As another example, you should often create different layouts for your activities, depending on the device’s screen orientation and size. For example, when the device screen is in portrait orientation (tall), you might want a layout with buttons to be vertical, but when the screen is in landscape orientation (wide), the buttons should be aligned horizontally. To change the layout depending on the orientation, you can define two different layouts and apply the appropriate qualifier to each layout’s directory name. Then, the system automatically applies the appropriate layout depending on the current device orientation.
安卓为可替换资源提供非常多的限定符。限定符是资源目录名称内的一个短字符串,用于定义设备配置应该使用哪些资源。另一个例子,你经常需要为你的activity创建不同的布局,其取决于设备的屏幕分辨率和尺寸。例如,当设备的屏幕在肖像方向模式(竖屏)下,你也许希望按钮的布局是垂直的,但是当屏幕是风景方向模式(横屏),按钮就应该水平的对齐。布局的改变取决于屏幕方向。,你可以定义两个不同的布局并为每个布局的目录名称应用合适限定符。然后,系统将根据当前设备的方向,自动的应用和合适的布局。

0 0
原创粉丝点击