from:http://blog.androgames.net/12/retrieving-data-asynchronously/
In Android, the system guards against applications that are insufficiently responsive for a period of time by displaying a dialog to the user, called the Application Not Responding (ANR) dialog. The user can choose to let the application continue, but the user won’t appreciate having this dialog displayed every time he or she uses your application
. So it’s important to design responsiveness into your application, so that the system never has cause to display an ANR to the user.
In this tutorial we are going to see how to perform asynchronous request to distant servers using the build’in HTTPClient without blocking the UI thread. the problem is that we have no possibilities to control the distant server responsiveness and the user Internet connection speed wich can cause the server’s response to be received after several seconds…
The problem to solve
The problem we want to solve is quite simple. Running an Activity, we want to fetch data from a distant server and process it without blocking the UI thread.
The solution
The Activity will react to a user action and send data to a distant server. The distant server will send back raw data to the application wich will produce processed data. The running Activity can then display the processed data to the user.
We need :
- An Activity running in the UI Thred
- A client to communicate with the distant server
- A thread to process the raw data
- A listener to pass the processed data back to the Activity
The source code
Our Activity will send data to the distant server with a static call on our client passing the request to send to the server and the callback listener to recieve the processed data.
Client.sendRequest(request, this);
A static method from our client will start a new AsynchronousSender in a new Thread
import android.os.Handler;
import org.apache.http.HttpRequest;
public class Client {
public static void sendRequest(final HttpRequest request,
ResponseListener callback) {
(new AsynchronousSender(request, new Handler(),
new CallbackWrapper(callback))).start();
}
}
The running Activity must implemment the ResponseListener interface to recieve the processed data from the server.
import org.apache.http.HttpResponse;
public interface ResponseListener {
public void onResponseReceived(HttpResponse response);
}
Finaly, the AsynchronousSender will send the request to the distant server and process the server’s response before passing the processed data back to the specified ResponseListener.
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpRequest;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.Handler;
public class AsynchronousSender extends Thread {
private static final DefaultHttpClient httpClient =
new DefaultHttpClient();
private Request request;
private Handler handler;
private CallbackWrapper wrapper;
protected AsynchronousSender(HttpRequest request,
Handler handler, CallbackWrapper wrapper) {
this.request = request;
this.handler = handler;
this.wrapper = wrapper;
}
public void run() {
try {
final HttpResponse response;
synchronized (httpClient) {
response = getClient().execute(request);
}
// process response
wrapper.setResponse(response);
handler.post(wrapper);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private HttpClient getClient() {
return httpClient;
}
}
We use a CallbackWrapper to send the processed data back to the Activity as the Hander needs a Runnable to post.
import org.apache.http.HttpResponse;
public class CallbackWrapper implements Runnable {
private ResponseListener callbackActivity;
private HttpResponse response;
public CallbackWrapper(ResponseListener callbackActivity) {
this.callbackActivity = callbackActivity;
}
public void run() {
callbackActivity.onResponseReceived(response);
}
public void setResponse(HttpResponse response) {
this.response = response;
}
}
分享到:
相关推荐
在Android开发中,网络通信是应用的核心功能之一,而`Android Asynchronous HTTPClient`(也称为AsyncHttpClient)是一个流行的库,用于实现异步HTTP请求,它使得开发者可以在不阻塞主线程的情况下执行网络操作,...
// 1.创建异步请求的客户端对象 ...其他有什么问题或者想具体了解详细说明,可以参考官网 http://loopj.com/android-async-http/ 其他参考链接 http://blog.csdn.net/redarmy_chen/article/details/26980613
"Asynchronous Android Programming" English | ISBN: 1785883240 | 2016 | 394 pages About This Book Construct scalable and performant applications to take advantage of multi-thread asynchronous ...
Asynchronous ...An asynchronous, callback-based Http client for Android built on top of Apache's HttpClient libraries. Changelog See what is new in version 1.4.9 released on 19th September 2015 ...
1. **HTTP 客户端**:在Android中,`HttpClient`曾是用于发送HTTP请求的库,但在API 22之后被标记为废弃,推荐使用`HttpURLConnection`或第三方库如OkHttp。不过,由于这个压缩包提到的是`HttpClient`,我们将讨论它...
Asynchronous programming has acquired immense importance in Android programming, especially when we want to make use of the number of independent processing units (cores) available on the most recent ...
本书《Asynchronous Android》主要讲述了在Android平台上如何处理异步任务,涵盖了AsyncTask、Handler、Looper、Loader、IntentService和AlarmManager等关键技术点。这些技术点对于开发响应迅速的Android应用至关...
《HttpClient Jar包详解》 HttpClient是Apache开源组织提供的一款强大的HTTP客户端编程库,它为Java开发者提供了方便的API,用于实现各种HTTP协议的功能,包括发送HTTP请求、接收响应、处理Cookies、管理连接池等。...
This library requires Android Asynchronous Http Client by James Smith. You have to maintain cookies with com.loopj.android.http.PersistentCookieStore class. Or you can try my fork of Android ...
An asynchronous, callback-based Http client for Android built on top of Apache's HttpClient libraries. Changelog See what is new in version 1.4.9 released on 19th September 2015 ...
Since the JavaScript language is single threaded, Node.js programs must make use of asynchronous callbacks and event loops managed by the runtime to ensure appli- cations remain responsive....
The .NET Framework provides three patterns for performing asynchronous operations: Asynchronous Programming Model (APM) pattern Event-based Asynchronous Pattern (EAP) Task-based Asynchronous Pattern ...
Asynchronous design has been an active area of research since at least the mid 1950’s, but has yet to achieve widespread use. We examine the benefits and problems inherent in asynchronous ...
Pro Asynchronous Programming with .NET teaches the essential skill of asynchronous programming in .NET. It answers critical questions in .NET application development, such as: how do I keep my program...
learning that uses asynchronous gradient descent for optimization of deep neural network controllers. We present asynchronous variants of four standard reinforcement learning algorithms and show that ...
However, he has soon learned that Android lacks a decent support for asynchronous programming (Async Task was/is a joke) while more reckless languages such as JavaScript had Promises for a long time....
[EBOOK]Asynchronous Circuit Design--Chris.J.Myers(包含源代码) With asynchronous circuit design becoming a powerful tool in the development of new digital systems, circuit designers are expected to ...
AJAX (Asynchronous JavaScript And XML)
11. 第11章“Developing Background Services and Asynchronous Code”讲述了如何开发后台服务以及编写异步代码,这对于改善应用性能和用户体验至关重要。 12. 第12章“Canvas and Drawables: Building Custom ...