Android 如何使用单独的线程来执行http请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3391272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use separate thread to perform http requests
提问by mbauer14
I have an application that is performing HTTP Requests (specifically calling the FogBugz API) when the user clicks certain buttons. Right now, I am just creating a service when the application starts, and then calling different methods in that service to complete requests. However, when I do this, there is the usual hang in the UI thread. I have looked at AsyncTask, but am not sure it will do what I want to accomplish. Because I need to instantly parse the XML that the HTTP Request returns, I need to have a process that is able to return this data to the UI thread. Will ASyncTask be able to accomplish this, or is there some other way?
我有一个应用程序在用户单击某些按钮时执行 HTTP 请求(特别是调用 FogBugz API)。现在,我只是在应用程序启动时创建一个服务,然后在该服务中调用不同的方法来完成请求。但是,当我这样做时,UI 线程中通常会挂起。我看过 AsyncTask,但不确定它会做我想要完成的事情。因为我需要立即解析 HTTP 请求返回的 XML,所以我需要一个能够将此数据返回到 UI 线程的进程。ASyncTask 能做到这一点,还是有其他方法?
public static InputStream makeRequest(String httpRequest)
{
In a separate thread, run HTTP Request, get back and process, return inputstream
}
This method is called by several others to perform HttpRequests. Once the inputstream is returned, the other methods parse for specific information.
此方法由其他几个调用以执行 HttpRequest。一旦输入流返回,其他方法就会解析特定信息。
回答by Chris Thompson
The simplest way to do it would just be to do something like
最简单的方法就是做类似的事情
//Body of your click handler
Thread thread = new Thread(new Runnable(){
@Override
public void run(){
//code to do the HTTP request
}
});
thread.start();
That will cause the code inside the run()
method to execute in a new thread of execution. You can look into an async task if you like although I've personally never used it. This is a quick and simple way to get things done.
这将导致run()
方法内的代码在新的执行线程中执行。如果您愿意,您可以查看异步任务,尽管我个人从未使用过它。这是完成工作的一种快速而简单的方法。
With regards to passing information back, I would use a Handler objectwhich effectively allows you to set up a message queue for a given thread and pass messages to it which cause the execution of specific code. The reason you need to do this is because Android will not let any thread other than the UI thread update the actual UI.
关于回传信息,我将使用Handler 对象,它有效地允许您为给定线程设置消息队列并将消息传递给它,从而导致执行特定代码。您需要这样做的原因是因为 Android 不会让 UI 线程以外的任何线程更新实际的 UI。
Does that address your question? I know my first pass didn't fully address all of your issues.
这是否解决了您的问题?我知道我的第一次通过并没有完全解决您的所有问题。
EditBasically, what you do is define a handler object in your Activity
like
编辑基本上,你要做的就是在你定义一个处理程序对象Activity
像
private Handler handler_ = new Handler(){
@Override
public void handleMessage(Message msg){
}
};
You also create static int
constants that help tell the handler what to do. You basically use those to allow for several different types of messages to be passed to one instance of a handler. If there is only going to be one message that is passed back, then you don't have to worry about that.
您还可以创建静态int
常量来帮助告诉处理程序该做什么。您基本上使用它们来允许将几种不同类型的消息传递给处理程序的一个实例。如果只有一条消息被传回,那么您不必担心。
For example
例如
private static final int UPDATE_UI = 1;
To send a message to the handler you call
向您调用的处理程序发送消息
handler_.sendMessage(Message.obtain(handler_, UPDATE_UI, inputStreamInstance));
From the handler:
从处理程序:
private Handler handler_ = new Handler(){
@Override
public void handleMessage(Message msg){
switch(msg.what){
case UPDATE_UI:
InputStream is = (InputStream)msg.obj;
//do what you need to with the InputStream
break;
}
}
};
Alternatively, where the inputStreamInstance is added to the Message
object, you can pass any object you like so if you wanted to parse it into some kind of container object or something like that, you could do that as well. Just cast it back to that object from within the handler.
或者,在将 inputStreamInstance 添加到Message
对象的地方,您可以传递您喜欢的任何对象,因此如果您想将其解析为某种容器对象或类似的东西,您也可以这样做。只需从处理程序中将其转换回该对象即可。
回答by Jin
Try using AsyncTask. Goto this Linkfor more:
尝试使用 AsyncTask。转到此链接了解更多:
private class SyncIncoData extends AsyncTask<String, String, String> {
ProgressBar pb;
ProgressBar pbar;
@Override
protected String doInBackground(String... urls) {
for (int i = 0; i <= 100; i++) {
publishProgress(i);
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pb = (ProgressBar) findViewById(R.id.progressBarsync4);
pb.setVisibility(View.VISIBLE);
}
@Override
protected void onPostExecute(String result) {
pb = (ProgressBar) findViewById(R.id.progressBarsync4);
pb.setVisibility(View.INVISIBLE);
}
@Override
protected void onProgressUpdate(String... values) {
pbar = (ProgressBar) findViewById(R.id.progressBarpbar);
pbar.setProgress(Integer.parseInt(values[0]));
super.onProgressUpdate(values);
}
}
Write the program for http request inside doinbackgroud()
写里面的http请求程序 doinbackgroud()