本文介绍了在Android的线程全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个问题。这里是我的code:
I have a problem. Here's my code:
public String getXmlFromUrl(String url) {
String xml = null;
new Thread(new Runnable() {
@Override
public void run() {
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).run();
// return XML
return xml;
}
那么,我该如何使用URL在我的主题,我怎么能返回XML?
So, how can I use url in my Thread and how can I return xml?
感谢您的帮助。
推荐答案
Android提供了一个AsyncTask的,这完全符合你的目标。
Android provides an AsyncTask, which perfectly fits your goal.
例如:
private class XMLTask extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
// Do stuff
// For example showing a Dialog to give some feedback to the user.
}
@Override
protected String doInBackground(.. parameters..) {
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return xml;
}
@Override
protected void onPostExecute(String xml) {
// If you have created a Dialog, here is the place to dismiss it.
// The `xml` that you returned will be passed to this method
xml.Dowhateveryouwant
}
}
}
这篇关于在Android的线程全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!