我的应用程序从站点读取 xml。我有这段代码来获取 xml 内容。
public String getPage(String url){
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build();
StrictMode.setThreadPolicy(policy);
BufferedReader in = null;
String data = null;
try
{
HttpClient client = new DefaultHttpClient();
URI website = new URI(url);
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
response.getStatusLine().getStatusCode();
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) !=null){
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
} finally{
if (in != null){
try{
in.close();
return data;
}catch (Exception e){
e.printStackTrace();
}
}
}
} catch (Exception e) {
//return e.toString();
return "No Internet Connection";
//e.printStackTrace();
}
}
我从这里调用它
public void axtarHandler_run(){
runOnUiThread(new Runnable() {
public void run() {
TextView axtarish_key = (TextView) findViewById(R.id.axtarish_key);
String netice;
try {
netice = getPage("http://somedomain.com/search.php?query="+URLEncoder.encode((String) axtarish_key.getText().toString(),"UTF-8"));
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
final XMLParser parser = new XMLParser();
String xml = netice; // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
final NodeList nl = doc.getElementsByTagName(KEY_SONG);
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
// adding HashList to ArrayList
songsList.add(map);
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(parentActivity, songsList, R.layout.list_row);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Element e = (Element) nl.item(position);
String music_id = parser.getValue(e, KEY_ID);
String music_name = parser.getValue(e, KEY_TITLE);
parentActivity.play_music_forsearch(Integer.toString(position), music_id, music_name);
}
});
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
但是当调用此方法时,应用程序会冻结一段时间。怎样成为?如何在后台执行此操作?