android相关文档中英文翻译_第1页
android相关文档中英文翻译_第2页
android相关文档中英文翻译_第3页
android相关文档中英文翻译_第4页
android相关文档中英文翻译_第5页
已阅读5页,还剩16页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Android Application FundamentalsAndroid applications are written in the Java programming language. The compiled Java code along with any data and resource files required by the application is bundled by the aapt tool into an Android package, an archive file marked by an .apk suffix. This file is the

2、 vehicle for distributing the application and installing it on mobile devices; its the file users download to their devices. All the code in a single .apk file is considered to be one application.In many ways, each Android application lives in its own world:(1) By default, every application runs in

3、its own Linux process. Android starts the process when any of the applications code needs to be executed, and shuts down the process when its no longer needed and system resources are required by other applications.(2) Each process has its own virtual machine (VM), so application code runs in isolat

4、ion from the code of all other applications.(3) By default, each application is assigned a unique Linux user ID. Permissions are set so that the applications files are visible only to that user and only to the application itself although there are ways to export them to other applications as well.It

5、s possible to arrange for two applications to share the same user ID, in which case they will be able to see each others files. To conserve system resources, applications with the same ID can also arrange to run in the same Linux process, sharing the same VM.1 Application ComponentsA central feature

6、 of Android is that one application can make use of elements of other applications (provided those applications permit it). For example, if your application needs to display a scrolling list of images and another application has developed a suitable scroller and made it available to others, you can

7、call upon that scroller to do the work, rather than develop your own. Your application doesnt incorporate the code of the other application or link to it. Rather, it simply starts up that piece of the other application when the need arises.For this to work, the system must be able to start an applic

8、ation process when any part of it is needed, and instantiate the Java objects for that part. Therefore, unlike applications on most other systems, Android applications dont have a single entry point for everything in the application (no main() function, for example). Rather, they have essential comp

9、onents that the system can instantiate and run as needed. There are four types of components:(1) ActivitiesAn activity presents a visual user interface for one focused endeavor the user can undertake. For example, an activity might present a list of menu items users can choose from or it might displ

10、ay photographs along with their captions. A text messaging application might have one activity that shows a list of contacts to send messages to, a second activity to write the message to the chosen contact, and other activities to review old messages or change settings. Though they work together to

11、 form a cohesive user interface, each activity is independent of the others. Each one is implemented as a subclass of the Activity base class.An application might consist of just one activity or, like the text messaging application just mentioned, it may contain several. What the activities are, and

12、 how many there are depends, of course, on the application and its design. Typically, one of the activities is marked as the first one that should be presented to the user when the application is launched. Moving from one activity to another is accomplished by having the current activity start the n

13、ext one.Each activity is given a default window to draw in. Typically, the window fills the screen, but it might be smaller than the screen and float on top of other windows. An activity can also make use of additional windows for example, a pop-up dialog that calls for a user response in the midst

14、of the activity, or a window that presents users with vital information when they select a particular item on-screen.The visual content of the window is provided by a hierarchy of views objects derived from the base View class. Each view controls a particular rectangular space within the window. Par

15、ent views contain and organize the layout of their children. Leaf views (those at the bottom of the hierarchy) draw in the rectangles they control and respond to user actions directed at that space. Thus, views are where the activitys interaction with the user takes place.For example, a view might d

16、isplay a small image and initiate an action when the user taps that image. Android has a number of ready-made views that you can use including buttons, text fields, scroll bars, menu items, check boxes, and more.A view hierarchy is placed within an activitys window by the Activity.setContentView() m

17、ethod. The content view is the View object at the root of the hierarchy. (See the separate User Interface document for more information on views and the hierarchy.)(2) ServicesA service doesnt have a visual user interface, but rather runs in the background for an indefinite period of time. For examp

18、le, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it. Each service extends the Service base class.A prime example is a media player playing songs from a play li

19、st. The player application would probably have one or more activities that allow the user to choose songs and start playing them. However, the music playback itself would not be handled by an activity because users will expect the music to keep playing even after they leave the player and begin some

20、thing different. To keep the music going, the media player activity could start a service to run in the background. The system would then keep the music playback service running even after the activity that started it leaves the screen.Its possible to connect to (bind to) an ongoing service (and sta

21、rt the service if its not already running). While connected, you can communicate with the service through an interface that the service exposes. For the music service, this interface might allow users to pause, rewind, stop, and restart the playback.Like activities and the other components, services

22、 run in the main thread of the application process. So that they wont block other components or the user interface, they often spawn another thread for time-consuming tasks (like music playback). See Processes and Threads, later.(3) Broadcast receiversA broadcast receiver is a component that does no

23、thing but receive and react to broadcast announcements. Many broadcasts originate in system code for example, announcements that the timezone has changed, that the battery is low, that a picture has been taken, or that the user changed a language preference. Applications can also initiate broadcasts

24、 for example, to let other applications know that some data has been downloaded to the device and is available for them to use.An application can have any number of broadcast receivers to respond to any announcements it considers important. All receivers extend the BroadcastReceiver base class.Broad

25、cast receivers do not display a user interface. However, they may start an activity in response to the information they receive, or they may use the NotificationManager to alert the user. Notifications can get the users attention in various ways flashing the backlight, vibrating the device, playing

26、a sound, and so on. They typically place a persistent icon in the status bar, which users can open to get the message.(4) Content providersA content provider makes a specific set of the applications data available to other applications. The data can be stored in the file system, in an SQLite databas

27、e, or in any other manner that makes sense. The content provider extends the ContentProvider base class to implement a standard set of methods that enable other applications to retrieve and store data of the type it controls. However, applications do not call these methods directly. Rather they use

28、a ContentResolver object and call its methods instead. A ContentResolver can talk to any content provider; it cooperates with the provider to manage any interprocess communication thats involved.See the separate Content Providers document for more information on using content providers.Whenever ther

29、es a request that should be handled by a particular component, Android makes sure that the application process of the component is running, starting it if necessary, and that an appropriate instance of the component is available, creating the instance if necessary.2 Activating components: intentsCon

30、tent providers are activated when theyre targeted by a request from a ContentResolver. The other three components activities, services, and broadcast receivers are activated by asynchronous messages called intents. An intent is an Intent object that holds the content of the message. For activities a

31、nd services, it names the action being requested and specifies the URI of the data to act on, among other things. For example, it might convey a request for an activity to present an image to the user or let the user edit some text. For broadcast receivers, theIntent object names the action being an

32、nounced. For example, it might announce to interested parties that the camera button has been pressed.There are separate methods for activating each type of component:(1). An activity is launched (or given something new to do) by passing an Intent object toContext.startActivity() or Activity.startAc

33、tivityForResult(). The responding activity can look at the initial intent that caused it to be launched by calling its getIntent() method. Android calls the activitys onNewIntent() method to pass it any subsequent intents. One activity often starts the next one. If it expects a result back from the

34、activity its starting, it calls startActivityForResult() instead of startActivity(). For example, if it starts an activity that lets the user pick a photo, it might expect to be returned the chosen photo. The result is returned in an Intent object thats passed to the calling activitys onActivityResu

35、lt() method.(2). A service is started (or new instructions are given to an ongoing service) by passing an Intent object to Context.startService(). Android calls the services onStart() method and passes it the Intent object. Similarly, an intent can be passed to Context.bindService() to establish an

36、ongoing connection between the calling component and a target service. The service receives the Intent object in an onBind() call. (If the service is not already running, bindService() can optionally start it.) For example, an activity might establish a connection with the music playback service men

37、tioned earlier so that it can provide the user with the means (a user interface) for controlling the playback. The activity would call bindService() to set up that connection, and then call methods defined by the service to affect the playback.A later section, Remote procedure calls, has more detail

38、s about binding to a service.(3). An application can initiate a broadcast by passing an Intent object to methods like Context.sendBroadcast(),Context.sendOrderedBroadcast(),Context.sendStickyBroadcast() in any of their variations.Android delivers the intent to all interested broadcast receivers by c

39、alling their onReceive() methods. For more on intent messages, see the separate article, Intents and Intent Filters.3 Shutting down componentsA content provider is active only while its responding to a request from a ContentResolver. And a broadcast receiver is active only while its responding to a

40、broadcast message. So theres no need to explicitly shut down these components.Activities, on the other hand, provide the user interface. Theyre in a long-running conversation with the user and may remain active, even when idle, as long as the conversation continues. Similarly, services may also rema

41、in running for a long time. So Android has methods to shut down activities and services in an orderly way:(1). An activity can be shut down by calling its finish() method. One activity can shut down another activity (one it started with startActivityForResult() by calling finishActivity().(2). A ser

42、vice can be stopped by calling its stopSelf() method, or by calling Context.stopService().Components might also be shut down by the system when they are no longer being used or when Android must reclaim memory for more active components. A later section, Component Lifecycles, discusses this possibil

43、ity and its ramifications in more detail.4 The manifest fileBefore Android can start an application component, it must learn that the component exists. Therefore, applications declare their components in a manifest file thats bundled into the Android package, the .apk file that also holds the applic

44、ations code, files, and resources.The manifest is a structured XML file and is always named AndroidManifest.xml for all applications. It does a number of things in addition to declaring the applications components, such as naming any libraries the application needs to be linked against (besides the

45、default Android library) and identifying any permissions the application expects to be granted.But the principal task of the manifest is to inform Android about the applications components.For example, an activity might be declared as follows:The name attribute of the element names the Activity subc

46、lass that implements the activity. The icon and label attributes point to resource files containing an icon and label that can be displayed to users to represent the activity.The other components are declared in a similar way elements for services, elements for broadcast receivers, and elements for

47、content providers. Activities, services, and content providers that are not declared in the manifest are not visible to the system and are consequently never run. However, broadcast receivers can either be declared in the manifest, or they can be created dynamically in code (as BroadcastReceiver obj

48、ects) and registered with the system by calling Context.registerReceiver().For more on how to structure a manifest file for your application, see The Android Manifest.xml File.5 Intent filtersAn Intent object can explicitly name a target component. If it does, Android finds that component (based on

49、the declarations in the manifest file) and activates it. But if a target is not explicitly named, Android must locate the best component to respond to the intent. It does so by comparing the Intent object to the intent filters of potential targets. A components intent filters inform Android of the k

50、inds of intents the component is able to handle. Like other essential information about the component, theyre declared in the manifest file. Heres an extension of the previous example that adds two intent filters to the activity:The first filter in the example the combination of the action android.i

51、ntent.action.MAIN and the ent.category.LAUNCHER is a common one. It marks the activity as one that should be represented in the application launcher, the screen listing applications users can launch on the device. In other words, the activity is the entry point for the application

52、, the initial one users would see when they choose the application in the launcher.The second filter declares an action that the activity can perform on a particular type of data.A component can have any number of intent filters, each one declaring a different set of capabilities. If it doesnt have

53、any filters, it can be activated only by intents that explicitly name the component as the target.For a broadcast receiver thats created and registered in code, the intent filter is instantiated directly as an IntentFilter object. All other filters are set up in the manifest.For more on intent filte

54、rs, see a separate document, Intents and Intent Filters.6 XML-Based LayoutWhile it is technically possible to create and attach widgets to our activity purely through Java code, the way we did in Chapter 4, the more common approach is to use an XML-based layout file. Dynamic instantiation of widgets

55、 is reserved for more complicated scenarios, where the widgets are not known at compile-time (e g., populating a column of radio buttons based on data retrieved off the Internet). With that in mind, its time to break out the XML and learn how to lay out Android activities that way. As the name sugge

56、sts, an XML-based layout is a specification of widgets relationships to each otherand to their containers (more on this in Chapter 7)encoded in XML format. Specifically, Android considers XML-based layouts to be resources, and as such layout files are stored in the res/layout directory inside your A

57、ndroid project. Each XML file contains a tree of elements specifying a layout of widgets and their containers that make up one view hierarchy. The attributes of the XML elements are properties, describing how a widget should look or how a container should behave. For example, if a Button element has

58、 an attribute value of android:textStyle = bold, that means that the text appearing on the face of the button should be rendered in a boldface font style. Androids SDK ships with a tool (aapt) which uses the layouts. This tool should be automatically invoked by your Android tool chain (e.g., Eclipse

59、, Ants build.xml). Of particular importance to you as a developer is that aapt generates the R.java source file within your project, allowing you to access layouts and widgets within those layouts directly from your Java code. XML as a GUI definition format is becoming more commonplace. Microsofts XAML2, Adobes Flex3, and

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论