我使用AsyncTask來下載網頁源代碼(HTML)。它工作正常,但需要很長時間才能執行..有沒有更好的方法。我認爲這是在UrlConnection中浪費時間。我試圖用HttpClient做到這一點,但無法獲得Html源代碼。幫助我使它快速或..告訴我如何把這個AsyncTask線程?在android中下載HTML的快速方法?
class RetrieveFeedTask extends AsyncTask<String, Void, String>
{
@Override
protected void onPreExecute()
{
super.onPreExecute();
Utilities.hideSoftKeyboard(PlayListActivity.this);
progressDialog = ProgressDialog.show(PlayListActivity.this,
"Loading...", "Please wait...");
}
@Override
protected String doInBackground(String... urls) {
try {
URL url= new URL(urls[0]);
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
String HTML_response = "";
while ((inputLine = br.readLine()) != null) {
// System.out.println(inputLine);
HTML_response += inputLine;
}
br.close();
System.out.println("Done");
Parser(feed);
return HTML_response;
} /*catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}*/catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(String feed)
{
super.onPostExecute(feed);
PlayListAdapter adapter = new PlayListAdapter(
PlayListActivity.this, list);
list_of_songs.setAdapter(adapter);
progressDialog.dismiss();
}
}
@SuppressLint("NewApi")
void Parser(String x)
{
if (x.contains(spliter_start))
{
if (spliter_end.isEmpty())
{
x = x.substring(x.indexOf(spliter_start));
}
else
{
x = x.substring(x.indexOf(spliter_start),
x.indexOf(spliter_end));
}
}
int i = 0;
list.clear();
while (x.contains(loop_controller))
{
if (i > 50)
{
break;
}
HashMap<String, String> map = new HashMap<String, String>();
x = x.substring(x.indexOf(song_start));
map.put("songsName",x.substring(
x.indexOf(song_start) + song_start.length(),
x.indexOf(song_end)));// songsName.get(i));
x = x.substring(x.indexOf(song_url_start));
map.put("songsUrl",x.substring(
x.indexOf(song_url_start) + song_url_start.length(),
x.indexOf(song_url_end)));// songsUrl.get(i));
list.add(map);
i++;
}
}
'AsyncTask'已經在'doInBackground()'中完成的工作使用後臺線程。使用Traceview來確定你的性能問題。最有可能的是,你需要將你的'Parser'工作移到'doInBackground()'中。 – CommonsWare
我已經嘗試過了,但是沒有我需要的那麼快?使用AsyncTask更好嗎 – Nepster
「使用Traceview確定性能問題的位置」是什麼部分你不明白嗎? – CommonsWare