




已阅读5页,还剩21页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
武汉理工大学毕业设计(论文)英文翻译学院(系): 信息工程学院 专业班级:学生姓名:指导教师: 基于 Android 平台的简易即时通信系统的设计与实现1Building and Consuming Services(构建和使用服务)The Android Platform provides a complete software stack. This means you get an operating system and middleware, as well as working applications (such as a phone dialer). Alongside all of this, you have an SDK that you can use to write applications for the platform. Thus far, weve seen that we can build applications that directly interact with the user through a user interface. We have not, however, discussed background services or the possibilities of building components that run in the background.In this chapter, we are going to focus on building and consuming services in Android. First well discuss consuming HTTP services, and then well cover a nice way to do simple background tasks, and finally well discuss interprocess communicationthat is,communication between applications on the same device. Then well go one step furtherand build a working example application that integrates with Googles Translate API. Android 平台提供了一个完整的软件栈。这意味着你可以获得一个操作系统和中间件,以及运行良好的应用程序(比如电话拨号程序)。除此之外,还有一个 SDK,可用于为该平台编写应用程序。迄今为止,我们知道可以构建能通过用户界面直接与用户交互的应用程序。但是,我们还未讨论后台服务或如何构建在后台运行的组件。本章将主要介绍在 Android 中构建和使用服务。首先将讨论使用 HTTP 服务,然后介绍一种较好的方法来执行简单的后台任务。最后讨论进程间通信,即同一设备上不通应用程序之间的通信。接下来将更进一步,构建能与 Google 的 Translate API 交互的可工作的实例应用程序。Consuming HTTP Services(使用 HTTP 服务)Android applications and mobile applications in general are small apps with a lot of functionality. One of the ways that mobile apps deliver such rich functionality on such a small device is that they pull information from various sources. For example, most Android smartphones come with the Maps application, which provides sophisticated mapping functionality. We, however, know that the application is integrated with the Google Maps API and other services, which provide most of the sophistication. That said, it is likely that the applications you write will also leverage information from other applications and APIs. A common integration strategy is to use HTTP. For example, you might have a Java servlet available on the Internet that provides services you want to leverage from one of your Android applications. How do you do that with Android? Interestingly, the Android SDK ships with a variation of Apaches HttpClient (/httpclient-3.x/), which is universally used within the J2EE space. The Android version has been modified for Android, but the APIs are very similar to the APIs in the J2EE version.基于 Android 平台的简易即时通信系统的设计与实现2The Apache HttpClient is a comprehensive HTTP client. Although it offers full support for the HTTP protocol, you will likely utilize only HTTP GET and POST. In this section, we will discuss using the HttpClient to make HTTP GET and HTTP POST calls.一般而言,Android 应用程序和移动应用程序是具有许多功能的小型应用程序。移动应用程序在这样的小型设备上实现此类富功能的一种方式是从各种来源获取信息。例如,大多数 Android 智能手机附带了 Maps 应用程序,该程序提供了复杂的地图功能。但是我们知道,该应用程序集成了 Google Maps API 和其他服务,它们提供了大部分的复杂功能。这也意味着,编写的应用程序也可以利用来自其他应用程序和 API 的信息。一种常用的集成策略是使用 HTTP。例如,英特网上可能有一个 Java servlet,它提供了一个你希望在一个 Android 应用程序使用的服务。那么如何通过 Android 利用该服务?有趣的是,Android SDK 附带了 Apache 的 HttpClient(/httpclient-3.x/),后者已在J2EE 领域得到广泛应用。Android 版本已做了相应的调整,但它的 API 与 J2EE 版本中的API 非常相似。Apache HttpClient 是一个完善的 HTTP 客户端。它提供了对 HTTP 协议的全面支持,可以使用 HTTP GET 和 POST。本节将介绍使用 HttpClient 来执行 HTTP GET 和 HTTP POST 调用。Using the HttpClient for HTTP GET Requests Heres one of the general patterns for using the HttpClient: 1. Create an HttpClient (or get an existing reference). 2. Instantiate a new HTTP method, such as PostMethod or GetMethod. 3. Set HTTP parameter names/values. 4. Execute the HTTP call using the HttpClient. 5. Process the HTTP response. Listing 111 shows how to execute an HTTP GET using the HttpClient.NOTE: We give you a URL at the end of the chapter which you can use to download projects fromthis chapter. This will allow you to import these projects into your Eclipse directly. Also, because the code attempts to use the Internet, you will need to add android.permission.INTERNET to your manifest file when making HTTP calls using the HttpClient.将 HttpClient 用于 HTTP GET 请求HttpClient 的一般使用模式如下。1 创建一个 HttpClient(或获取现有的引用)。2 实例化新 HTTP 方法,比如 PostMethod 或 GetMethod。3 设置 HTTP 参数名称/值。4 使用 HttpClient 执行 HTTP 调用。基于 Android 平台的简易即时通信系统的设计与实现35 处理 HTTP 响应。代码清单 1-1 演示了如何使用 HttpClient 执行 HTTP GET。说明:本章最后将给出一个 URL,通过该 URL 可下载本章的项目。下载后,可将这些项目直接导入 Eclipse。此外,由于这段代码会尝试使用因特网,所以在使用 HttpClient 执行HTTP 调用时,需要将 Android.peimission.INTERNET 添加到描述文件中。The HttpClient provides abstractions for the various HTTP request types, such as HttpGet, HttpPost, and so on. Listing 11 uses the HttpClient to get the contents of the /android/ URL. The actual HTTP request is executed with the call to client.execute(). After executing the request, the code reads the entire response into a string object. Note that the BufferedReader is closed in the finally block, which also closes the underlying HTTP connection. For our example we embedded the HTTP logic inside of an activity, but we dont need to be within the context of an activity to use HttpClient. You can use it from within the context of any Android component or use it as part of a standalone class. In fact, you really shouldnt use HttpClient directly within an activity, since a web call could take a while to complete and cause the activity to be force closed. Well cover that topic later in this chapter. For now were going to cheat a little so we can focus on how to make HttpClient calls.The code in Listing 11 executes an HTTP request without passing any HTTP parameters to the server. You can pass name/value parameters as part of the request by appending name/value pairs to the URL, as shown in Listing 12.Listing 12. Adding Parameters to an HTTP GET Request HttpGet request = new HttpGet(http:/somehost/WS2/Upload.aspx?one=valueGoesHere); client.execute(request);When you execute an HTTP GET, the parameters (names and values) of the request arepassed as part of the URL. Passing parameters this way has some limitations. Namely,the length of a URL should be kept below 2,048 characters. If you have more than this amount of data to submit, you should use HTTP POST instead. The POST method is more flexible and passes parameters as part of the request body.HttpClient 为各种类型的 HTTP 请求提供了抽象,比如 HttpGet、HttpPost 等。代码 1-1 使用 HttpClient 获取 /android/ URL 的内容。实际的 HTTP 请求是通过调用 client.execute()来执行的。执行请求之后。代码将完整的响应信息读取到一个字符串对象中。请注意,BufferedReader 在 finally 代码块中关闭,同时也关闭了基础 HTTP连接。对于我们的实例,我们将 HTTP 逻辑嵌入到一个活动内,但无需位于活动上下文内即可使用 HttpClient。可以从任何 Android 组件上下文内使用它,或者作为一个独立类的一部分来使用它。事实上,确实不应该在活动内直接使用 HttpClient,因为网络调用可能需基于 Android 平台的简易即时通信系统的设计与实现4要一段时间才能完成,因而有可能会导致活动被强制关闭。本章后面将介绍该主题。现在我们将注意力集中在如何执行 HttpClient 调用上。代码清单 1-1 中的代码执行一个 HTTP 请求,但未向服务器传递任何 HTTP 参数。将名称/值对附加到 URL 之后,可以将名称/值参数作为请求的一部分来传递,如代码清单1-2 所示。代码清单 1-2 向 HTTP GET 请求添加参数HttpGet request = new HttpGet(http:/somehost/WS2/Upload.aspx?one=valueGoesHere); client.execute(request);当执行 HTTP GET 时,请求的参数(名称和值)作为 URL 的一部分来传递。以这种方式传递参数具有一些不足。即 URL 的长度应该保持在 2048 个字符以内。如果要提交的数据超过这个数量,应该使用 HTTP POST。POST 方法更加灵活,它将参数作为请求的主体的一部分传递。Using the HttpClient for HTTP POST Requests (a Multipart Example)Making an HTTP POST call is very similar to making an HTTP GET call (see Listing 113).The code in Listing 13 would replace the 3 lines in Listing 111 where the HttpGet isused. Everything else could stay the same. To make an HTTP POST call with theHttpClient, you have to call the execute() method of the HttpClient with an instance of HttpPost. When making HTTP POST calls, you generally pass URL-encoded name/value form parameters as part of the HTTP request. To do this with the HttpClient, you have to create a list that contains instances of NameValuePair objects and then wrap that list with a UrlEncodedFormEntity object. The NameValuePair wraps a name/value combination and the UrlEncodedFormEntity class knows how to encode a list of NameValuePair objects suitable for HTTP calls (generally POST calls). After you create a UrlEncodedFormEntity, you can set the entity type of the HttpPost to the UrlEncodedFormEntity and then execute the request.In Listing 13, we created an HttpClient and then instantiated the HttpPost with the URL of the HTTP endpoint. Next, we created a list of NameValuePair objects and populated it with several name/value parameters. We then created a UrlEncodedFormEntity instance, passing the list of NameValuePairobjects to its constructor. Finally, we called the setEntity() method of the POST request and then executed the request using the HttpClient instance.HTTP POST is actually much more powerful than this. With an HTTP POST, we can pass simple name/value parameters, as shown in Listing 113, as well as complex parameters such as files. HTTP POST supports another request-body format known as a multipart POST. With this type of POST, you can send name/value parameters as before, along with arbitrary files. Unfortunately, the version of HttpClient shipped with Android does not directly support multipart POST. To do multipart POST calls, you need to get three additional Apache open 基于 Android 平台的简易即时通信系统的设计与实现5source projects: Apache Commons IO, Mime4j, and HttpMime. You can download these projects from the following web sites: Commons IO: /io/ Mime4j: /mime4j/ HttpMime: /downloads.cgi (inside of HttpClient) Alternatively, you can visit this site to download all of the required .jar files to do multipart POST with Android: /book/view/1430226595NOTE: The multipart example uses several .jar files that are not included as part of the Android runtime. To ensure that the .jar files will be packaged as part of your .apk file, you need to add them as external .jar files in Eclipse. To do this, right-click your project in Eclipse, select Properties, choose Java Build Path, select the Libraries tab, and then select Add External JARs. Following these steps will make the .jar files available during compile time as well as runtime.To execute a multipart POST, you need to create an HttpPost and call its setEntity() method with a MultipartEntity instance (rather than the UrlEncodedFormEntity we created for the name/value parameter form post). MultipartEntity represents the body of a multipart POST request. As shown, you create an instance of a MultipartEntity and then call the addPart() method with each part. Listing 14 adds three parts to the request: two string parts and an XML file.Finally, if you are building an application that requires you to pass a multipart POST to a web resource, youll likely have to debug the solution using a dummy implementation of the service on your local workstation. When youre running applications on your local workstation, normally you can access the local machine by using localhost or IP address . With Android applications, however, you will not be able to use localhost (or ) because the emulator will be its own localhost. You dont want to point this client to a service on the Android device, you want to point to your workstation. To refer to your development workstation from the application running in the emulator, youll have to use your workstations IP address. (Refer back to Chapter 2 if you need help figuring out what your workstations IP address is.) You will need to modify Listing 14 by substituting the IP address with the IP address of your workstation.将 HttpClient 用于 HTTP POST 请求(多部分 POST 请求示例)执行 HTTP POST 调用与执行 HTTP GET 调用非常相似(参见代码清单 1-3)。代码清单 1-3 使用 HttpClient 发出 HTTP POST 请求代码清单 1-3 将代码清单 1-1 中使用 HttpGet 的 3 行换成新代码。要使用 HttpClient 执行 Http Post 调用,必须通过一个 HttpPost 实例调用 HttpClient 的 execute()方法。当执行HTTP Post 调用时,通常将编码到 URL 中的名称/值对参数作为 HTTP 请求的一部分传递。基于 Android 平台的简易即时通信系统的设计与实现6要通过 HttpClient 实现此目的,必须创建一个包含 NameValuePair 对象实例的列表,然后使用 UrlEncodedFormEntity 对象包装该列表。NameValuePair 包转了一个名称/ 值组合,UrlEncodeFormEntity 类知道如何编码适合 HTTP 调用(通常为 POST 调用)的NameValuePair 对象列表。创建 UrlEncodedFormEntity 之后,可以将 HttpPost 的实体类型设置为 UrlEncodedForm Entity,然后执行该请求。在代码清单 1-3 中,我们创建了一个 HttpClient,然后使用 HTTP 端点的 URL 实例化了 HttpPost。接下来,将创建一个 NameValuePair 对象列表并填充几个名称/ 值参数。然后创建一个 UrlEncodedFormEntiy 实例,将 NameValuePairobjects 列表传递给它的构造函数。最后调用 POST 请求的 setEntity()方法,然后使用 HttpClient 实例执行请求。实际上,HTTP Post 的功能比这强大的多。使用 HTTP POST,我们可以传递简单的名称/ 值参数(如代码清单 1-3 所示),也可以传递复杂的参数,如文件。 HTTP POST 支持另一种称为多部分 POST 的请求主体格式。使用这种 POST 类型,可以像前面一样发送名称/ 值参数,也可以发送任意文件。不幸的是,Android 随带的 HttpClient 版本无法直接支持多部分 POST。要执行多部分 POST 调用,需要获取另外 3 个 Apache 开源项目:Apache Commons IO、Mime4J 和 HttpMine。可以从以下网站下载这些项目。Commons IO: /io/ Mime4j: /mime4j/ HttpMime: /downloads.cgi (inside of HttpClient) 也可以从下面这个网站下载在 Android 中执行多部分 POST 所需的所有.jar 文件:/book/view/1430226595代码清单 1-4 演示了一个使用 Android 的多部分 POST。说明:这个多部分 POST 示例使用了几个.JAR 文件,这些文件未包含在 Android 运行时中。要确保将这些.jar 文件打包到.apk 文件中,需要在 Eclipse 中添加外部.jar 文件。要做到这一点,在 Eclipse 中右键单击您的项目,选择属性,选择 Java 构建路径,选择Libraries 选项卡,然后选择“添加外部 JAR”。以下这些步骤将 .jar 文件,以及在编译时可用运行。执行一个多部分 POST,你需要创建 HttpPost,并使用 MultipartEntity 实例(而不是我们的名称/值参数表格后创建的 UrlEncodedFormEntity)来调用 setEntity()方法。MultipartEntity 代表一个多部分 POST 请求体。如上例所示,你创建一个 MultipartEntity的实例,然后使用每部分调用的 addPart()方法。清单 1-4 向请求增加了三个部分:两个字符串部分和 XML 文件。最后,如果构建的应用程序要求需要通过多部分 POST 传递给 Web 资源,可能必须在本地工作站上使用服务的伪实现调试解决方案。当你在本地工作站上运行的应用程序,通常可以通过使用 localhost 或 IP 地址 访问本地计算机。与 Android 应用程序,然而,你将不能够使用 localhost(或 ),因为模拟器将其自己的本地主机。你不想指出这个客户端在 Android 设备上的服务,你要指向您的工作站。要从在模拟器上运行基于 Android 平台的简易即时通信系统的设计与实现7的应用程序应用开发工作站,你必须使用工作站的 IP 地址。 (请参阅第 2 章,如果你需要帮助搞清楚工作站的 IP 地址是什么。),您将需要修改 1-4 代码,将工 IP 地址替换成工作站的 IP 地址。Addressing Multithreading Issues(解决多线程问题)The examples weve shown so far created a new HttpClient for each request. In practice, however, you should probably create one HttpClient for the entire application and use that for all of your HTTP communication. With one HttpClient servicing all of your HTTP requests, you should also pay attention to multithreading issues that could surface if you make simultaneous requests through the same HttpClient. Fortunately, the HttpClient provides facilities that make this easyall you have to do is create the DefaultHttpClient using a ThreadSafeClientConnManager, as shown in Listing 16. 到目前为止介绍的例子为每个请求创建一个新的 HttpClient。然而,在实践中,应该为整个应用程序创建一个 HttpClient,并且使用到所有 HTTP 通信。除了将一个 HttpClient的服务应用所有 HTTP 请求,也应该注意通过相同的 HttpClient 同时发出多个请求时可能发生的多线程的问题。幸运的是,HttpClient 提供了一些工具来简化这个任务,你所需要做的只是使用 ThreadSafeClientConnManager 创建 DefaultHttpClient,如代码清单 1-6 所示。If your application needs to make more than a few HTTP calls, you should create an HttpClient that services all your HTTP requests. The simplest way to do this is to create a singleton class that can be accessed from anywhere in the application, as weve shown here. This is a fairly standard Java pattern in which we synchronize access to a getter method, and that getter method returns the one and only HttpClient object for the singleton, creating it the first time as necessary.如果应用程序需要执行几个 HTTP 调用,则应该创建一个为所有的 HTTP 请求服务的 HttpClient。做到这一点最简单的方法是创建一个单独的类,可以从应用程序中的任何地方来访问它,就像这里展示一样。这是一个相当标准的 Java 模式,在我们访问一个getter 方法,这个 getter 方法返回一个 HttpClient 对象,这个对象在第一次需要时创建。Now, take a look at the getHttpClient() method of CustomHttpClient. This method is responsible for creating our singleton HttpClient. We set some basic parameters, some timeout values, and the schemes that our HttpClient will support (i.e., HTTP and HTTPS). Notice that when we instantiate the DefaultHttpClient(), we pass in a ClientConnectionManager. The ClientConnectionManager is responsible for managing HTTP connections for the HttpClient. Because we want to use a single HttpClient for all the HTTP requests (requests which could overlap if were using threads), we create a ThreadSafeClientConnManager.现在,让我们看看 CustomHttpClient 中 getHttpClient ()方法。这种方法是负责创建我们的单例 HttpClient。我们设置了一些基本参数,一些超时值以及该 HttpClient 会支持基于 Android 平台的简易即时通信系统的设计与实现8(例如,HTTP 和 HTTPS)的模式。请注意,当我们实例化的 DefaultHttpClient(),我们传入了一个 ClientConnectionManager。ClientConnectionManager 是负责管理 HttpClient的 HTTP 连接。因为我们想用一个 HttpClient 用于所有 HTTP 请求(如果使用线程,请求可以重叠),所以我们创建了一个 ThreadSafeClientConnManager。We also show you a simpler way of collecting the response from the HTTP request, using a BasicResponseHandler. The code for our activity that uses our CustomHttpClient is in Listing 17. 我们也告诉你一个简单的方法收集从 HTTP 请求的响应,使用BasicResponseHandler。使用 CustomHttpClient 的活动的代码如清单代码 1-7。For this sample application, we do a simple HTTP get of the Google home page. We also use a BasicResponseHandler object to take care of rendering the page as a big String, which we then write out to LogCat. As you can see, adding a BasicResponseHandler to the execute() method is very easy to do.对于这个示例应用程序,我们对谷歌主页做一个简单的 HTTP GET 请求。我们还可以使用 BasicResponseHandler 对象作为一个大 String,我们然后写出 LogCat 的页面。正如你可以看到,在将 BasicResponseHandler 添加到 execute()方法中是很容易做到的。You may be tempted to take advantage of the fact that each Android application has an associated Application object. By default, if you dont define a custom application object, Android uses android.app.Application. Heres the interesting thing about the application object: there will always be exactly one application object for your application, and all of your components can access it (using the global context object). It is possible to extend the Application class and add functionality such as our CustomHttpClient. However, in our case there is really no reason to do this within the Application class itself, and you will be much better off not messing with the Application class when you can simply create a separate singleton class to handle this type of need.你可能会考虑到一个事实,即每个 Android 应用程序都有一个相关联的 Application 对象的。默认情况下,如果你不定义一个自定义的应用程序对象,Android 使用android.app.Application。下面是关于应用程序对象的有趣的事情:总是会有一个为您的应用程序的应用程序对象,所有组件可以访问它(使用全局上下文的对象)。这是可能的扩展 Application 类并添加功能,例如我们的 CustomHttpClient。然
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025秋统编版(2024)新教材三年级语文上册第七单元《语文园地七》练习题及答案
- 特种玻璃电子束切割超硬涂层工艺考核试卷及答案
- 印染烘干操作工综合考核试卷及答案
- 电机铁芯叠装工异常处理考核试卷及答案
- 印后成型工数字化技能考核试卷及答案
- 信息技术考试ps试题及答案
- 有限空间作业及企业安全管理风险管控与隐患治理试卷
- 银行综合试题及答案
- 银行债务员面试题目及答案
- 银行押运员面试题及答案
- 2025年医疗工作人员定向招聘考试笔试试题(含答案)
- 第二单元混合运算单元测试卷(含答案) 2025-2026学年人教版三年级数学上册
- 超声引导下经支气管针吸活检术核心组织采集率的影响因素分析介绍演示培训课件
- 绘本《其实我很喜欢你》冯玉梅
- 铸牢中华民族共同体意识主题班会
- 公司内部审计制度范本(四篇)
- 绿色建筑材料和建筑设备
- 可靠性试验管理办法
- 蓄电池组充放电记录表格格式模板
- 智慧交通典型城市案例及启示
- 国家开放大学《人文英语4》边学边练参考答案
评论
0/150
提交评论