我有一个android应用程序,我从多个url提取数据,然后保存为字符串的数组列表。它工作得很好,但是从13个url中获取数据,它需要接近15-20秒。而从同一组url中获取数据需要3-4秒,在使用phonegap构建的同一个应用程序中。下面是代码。
@Override
protected String doInBackground(String... params) {
client = new DefaultHttpClient();
for(int i=0;i<url.size();i++)
{
get = new HttpGet(url.get(i));
try {
response = client.execute(get);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
entity = response.getEntity();
InputStream is = null;
try {
is = entity.getContent();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = null;
do {
try {
line = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
buffer.append(line);
} while (line != null);
String str = buffer.toString();
param.add(str);
}
return null;
}
谁能建议我如何加快这个执行和减少提取时间。
您可以尝试为for循环的每次迭代启动一个单独的线程。像这样:
for(int i = 0; i < url.size(); i++){
//start thread that gets data from url and adds it to the list
}