翻译翻的想吐

Handler

Class Overview


A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.

Scheduling messages is accomplished with the post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, long), sendEmptyMessage(int), sendMessage(Message), sendMessageAtTime(Message, long), and sendMessageDelayed(Message, long) methods. The post versions allow you to enqueue Runnable objects to be called by the message queue when they are received; the sendMessage versions allow you to enqueue a Message object containing a bundle of data that will be processed by the Handler's handleMessage(Message) method (requiring that you implement a subclass of Handler).

When posting or sending to a Handler, you can either allow the item to be processed as soon as the message queue is ready to do so, or specify a delay before it gets processed or absolute time for it to be processed. The latter two allow you to implement timeouts, ticks, and other timing-based behavior.

When a process is created for your application, its main thread is dedicated to running a message queue that takes care of managing the top-level application objects (activities, broadcast receivers, etc) and any windows they create. You can create your own threads, and communicate back with the main application thread through a Handler. This is done by calling the same post or sendMessage methods as before, but from your new thread. The given Runnable or Message will then be scheduled in the Handler's message queue and processed when appropriate.

类概述

一个处理程序员允许您发送和过程Message和Runnable对象关联到一个线程的MessageQueue.每个处理程序实例相关联的单个线程和线程的消息队列,当你创建一个新的处理程序。它绑定到线程/线程的消息队列创建它---才能够那时起,它将提供消息和runnables消息队列和执行他们的消息队列。

处理程序有两个主要用途(1)调度信息和执行runnable在将来的某个时间点,和(2)排队一个动作比你自己的一个不同的线程上执行。

完成的调度信息post(Runnable),postAtTime(Runnable,long),postDelayed(Runnable,long),sendEmptyMessage(int),sendMessage(Message),sendMessageAtTime(Message,long),sendMessageDelayed(Message,long)方法。发布版本允许您将Runnable对象被称为由消息队列时收到;sendMessage版本允许您将一个Message对象包含一个包的数据将由处理程序的处理handleMessage(Message)方法(处理程序要求您实现一个子类)。

发布或发送到处理程序时,您可以允许项目紧靠处理消息队列准备这样做,或指定一个延迟之前加工处理或绝对时间,后两个允许您实现超时,和其他timing-base行为。为应用程序创建进程时,其主要致力于运行一个线程消息,负责管理项级应用程序对象(活动、广播接收器等)和他们创建的任何windows。您可以创建自己的线程,并且与主应用程序线程通信通过一个处理程序。这是通过调用相同的帖子或sendMessage方法和之前一样,但从你的新线程,给定的Runnable或消息被安排在处理程序的消息队列,并在适当的时候处理

Looper

Class Overview


Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.

Most interaction with a message loop is through the Handler class.

This is a typical example of the implementation of a Looper thread, using the separation of prepare() and loop() to create an initial Handler to communicate with the Looper.

  class LooperThread extends Thread { 
      public Handler mHandler; 
 
      public void run() { 
          Looper.prepare(); 
 
          mHandler = new Handler() { 
              public void handleMessage(Message msg) { 
                  // process incoming messages here 
              } 
          }; 
 
          Looper.loop(); 
      } 
  }

类用于运行一个消息循环的线程,默认情况下没有一个消息循环的线程与他们联系在一起,创建一个prepare()在运行的线程循环,然后loop()它处理消息,直到停止循环。

大多数与一个消息循环是通过交互Handle类。

这是一个典型的列子的实现底线分线,使用的分离prepare()和loop()创建一个初始化处理程序与它进行通信

MessageQueue

Class Overview


Low-level class holding the list of messages to be dispatched by a Looper. Messages are not added directly to a MessageQueue, but rather through MessageQueue.IdleHandler objects associated with the Looper.

You can retrieve the MessageQueue for the current thread with Looper.myQueue().

低级类控股派出的消息列表Looper。消息不实直接添加MessageQueue,而是通过MessageQueue。IdleHandler与之相关的对象。您可以检索的MessageQueue当前线程Looper.myQueue()。

HttpURLConnection

Class Overview


An URLConnection for HTTP (RFC 2616) used to send and receive data over the web. Data may be of any type and length. This class may be used to send and receive streaming data whose length is not known in advance.

Uses of this class follow a pattern:

  1. Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to HttpURLConnection.
  2. Prepare the request. The primary property of a request is its URI. Request headers may also include metadata such as credentials, preferred content types, and session cookies.
  3. Optionally upload a request body. Instances must be configured with setDoOutput(true) if they include a request body. Transmit data by writing to the stream returned by getOutputStream().
  4. Read the response. Response headers typically include metadata such as the response body's content type and length, modified dates and session cookies. The response body may be read from the stream returned by getInputStream(). If the response has no body, that method returns an empty stream.
  5. Disconnect. Once the response body has been read, the HttpURLConnection should be closed by calling disconnect(). Disconnecting releases the resources held by a connection so they may be closed or reused.

For example, to retrieve the webpage at http://www.android.com/:

   URL url = new URL("http://www.android.com/"); 
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
   try { 
     InputStream in = new BufferedInputStream(urlConnection.getInputStream()); 
     readStream(in); 
    finally { 
     urlConnection.disconnect(); 
   } 
 }

Secure Communication with HTTPS

Calling openConnection() on a URL with the "https" scheme will return an HttpsURLConnection, which allows for overriding the default HostnameVerifier and SSLSocketFactory. An application-supplied SSLSocketFactory created from an SSLContext can provide a custom X509TrustManager for verifying certificate chains and a custom X509KeyManager for supplying client certificates. See HttpsURLConnection for more details.

Response Handling

HttpURLConnection will follow up to five HTTP redirects. It will follow redirects from one origin server to another. This implementation doesn't follow redirects from HTTPS to HTTP or vice versa.

If the HTTP response indicates that an error occurred, getInputStream() will throw an IOException. Use getErrorStream() to read the error response. The headers can be read in the normal way using getHeaderFields(),

Posting Content

To upload data to a web server, configure the connection for output using setDoOutput(true).

For best performance, you should call either setFixedLengthStreamingMode(int) when the body length is known in advance, or setChunkedStreamingMode(int) when it is not. Otherwise HttpURLConnection will be forced to buffer the complete request body in memory before it is transmitted, wasting (and possibly exhausting) heap and increasing latency.

For example, to perform an upload:

   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
   try { 
     urlConnection.setDoOutput(true); 
     urlConnection.setChunkedStreamingMode(0); 
 
     OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream()); 
     writeStream(out); 
 
     InputStream in = new BufferedInputStream(urlConnection.getInputStream()); 
     readStream(in); 
    finally { 
     urlConnection.disconnect(); 
   } 
 }

Performance

The input and output streams returned by this class are not buffered. Most callers should wrap the returned streams with BufferedInputStream or BufferedOutputStream. Callers that do only bulk reads or writes may omit buffering.

When transferring large amounts of data to or from a server, use streams to limit how much data is in memory at once. Unless you need the entire body to be in memory at once, process it as a stream (rather than storing the complete body as a single byte array or string).

To reduce latency, this class may reuse the same underlying Socket for multiple request/response pairs. As a result, HTTP connections may be held open longer than necessary. Calls to disconnect() may return the socket to a pool of connected sockets. This behavior can be disabled by setting the http.keepAlive system property to false before issuing any HTTP requests. The http.maxConnections property may be used to control how many idle connections to each server will be held.

By default, this implementation of HttpURLConnection requests that servers use gzip compression. Since getContentLength() returns the number of bytes transmitted, you cannot use that method to predict how many bytes can be read from getInputStream(). Instead, read that stream until it is exhausted: when read() returns -1. Gzip compression can be disabled by setting the acceptable encodings in the request header:

   urlConnection.setRequestProperty("Accept-Encoding", "identity"); 
 

Handling Network Sign-On

Some Wi-Fi networks block Internet access until the user clicks through a sign-on page. Such sign-on pages are typically presented by using HTTP redirects. You can use getURL() to test if your connection has been unexpectedly redirected. This check is not valid until after the response headers have been received, which you can trigger by calling getHeaderFields() or getInputStream(). For example, to check that a response was not redirected to an unexpected host:
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
   try { 
     InputStream in = new BufferedInputStream(urlConnection.getInputStream()); 
     if (!url.getHost().equals(urlConnection.getURL().getHost())) { 
       // we were redirected! Kick the user out to the browser to sign on? 
      
     ... 
   } finally { 
     urlConnection.disconnect(); 
   } 
 }

HTTP Authentication

HttpURLConnection supports HTTP basic authentication. Use Authenticator to set the VM-wide authentication handler:
   Authenticator.setDefault(new Authenticator() { 
     protected PasswordAuthentication getPasswordAuthentication() { 
       return new PasswordAuthentication(username, password.toCharArray()); 
      
   }); 
 }
Unless paired with HTTPS, this is not a secure mechanism for user authentication. In particular, the username, password, request and response are all transmitted over the network without encryption.

Sessions with Cookies

To establish and maintain a potentially long-lived session between client and server, HttpURLConnection includes an extensible cookie manager. Enable VM-wide cookie management using CookieHandler and CookieManager:
   CookieManager cookieManager = new CookieManager(); 
   CookieHandler.setDefault(cookieManager); 
 
By default, CookieManager accepts cookies from the origin server only. Two other policies are included: ACCEPT_ALL and ACCEPT_NONE. Implement CookiePolicy to define a custom policy.

The default CookieManager keeps all accepted cookies in memory. It will forget these cookies when the VM exits. Implement CookieStore to define a custom cookie store.

In addition to the cookies set by HTTP responses, you may set cookies programmatically. To be included in HTTP request headers, cookies must have the domain and path properties set.

By default, new instances of HttpCookie work only with servers that support RFC 2965 cookies. Many web servers support only the older specification, RFC 2109. For compatibility with the most web servers, set the cookie version to 0.

For example, to receive www.twitter.com in French:

   HttpCookie cookie = new HttpCookie("lang", "fr"); 
   cookie.setDomain("twitter.com"); 
   cookie.setPath("/"); 
   cookie.setVersion(0); 
   cookieManager.getCookieStore().add(new URI("http://twitter.com/"), cookie); 
 

HTTP Methods

HttpURLConnection uses the GET method by default. It will use POST if setDoOutput(true) has been called. Other HTTP methods (OPTIONS, HEAD, PUT, DELETE and TRACE) can be used with setRequestMethod(String).

Proxies

By default, this class will connect directly to the origin server. It can also connect via an HTTP or SOCKS proxy. To use a proxy, use URL.openConnection(Proxy) when creating the connection.

IPv6 Support

This class includes transparent support for IPv6. For hosts with both IPv4 and IPv6 addresses, it will attempt to connect to each of a host's addresses until a connection is established.

Response Caching

Android 4.0 (Ice Cream Sandwich, API level 15) includes a response cache. See android.net.http.HttpResponseCache for instructions on enabling HTTP caching in your application.

Avoiding Bugs In Earlier Releases

Prior to Android 2.2 (Froyo), this class had some frustrating bugs. In particular, calling close() on a readable InputStream could poison the connection pool. Work around this by disabling connection pooling:
   private void disableConnectionReuseIfNecessary() { 
   // Work around pre-Froyo bugs in HTTP connection reuse. 
   if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) { 
     System.setProperty("http.keepAlive", "false"); 
    
 }}

Each instance of HttpURLConnection may be used for one request/response pair. Instances of this class are not thread safe.

 

一个URLConnection对于HTTP(RFC2616)用于通过网络发送和接收数据,数据可能是任何类型和长度,这个类可以用来发送和接收流数据的长度是事先不知道的

使用这个类遵循的一个模式:

1获得一个新的HttpURLConnection通过调用URL.openConnection()和结果HttpURLConnection

2准备请求的主要属性时它的URI请求,请求头也包括元数据,如凭证,。首选内容类型和活化cookie

3选择上传提请求主题。必须配置实例setDoOutput(true)如果他们包含请求主体。返回的流传输数据通过编写getOutputStream()

4读取响应。响应头通常包括元数据,如响应主题的内容类型和长度。修改日期和会话cookie,程序的反应可能会读取返回的流getInputStream()如果响应没有,则该方法无效

5断开连接。一旦读取响应主体,HttpURLConnection应该关闭通过调用disconnect()断开释放所持有的资源连接,所以他们可能会关闭或重用。

安全的通信,并通过HTTPS

调用openConnection()在一个URL将返回一个“https”计划HttpsURLConnection,它允许覆盖默认值HOST那么Verifier和SSLSocketFactory。一个application-supplied SSLsocketFactory创建从一个SSLContext可以提供一个自定义X509TrustManager为验证证书链和一个定制的X509KeyManager提供客户端证书。看到HttpsURLConnection为更多的细节

响应处理

HttpURLConnection将跟进五HTTP重定向,它从一个源服务器将会重定向到另一个地方,这个实现不遵循HTTP重定向从HTTPS,反之亦然,如果HTTP响应表面发送了错误,getInputStream()将抛出一个IOException。使用getErrorStream()读取错误响应。头可以正常读取的方式使用getHeaderFields()

发布内容

上传数据到一个Web服务器,配置连接输出使用setDoOutput(true).最佳性能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值