我有一个关于加速文本文件加载的问题。可能有类似的线索,但很难找到。加速使用ASyncTask获取文件
我有一个有趣的设置。启动时,应用程序会联系我的服务器以获取最新数据。这基本上是一个长文本文件,其中包含一些应用程序信息以及最新的数据。这工作得很好。有一个ASyncTask服务可以做到这一点。我已经包含了下面任务的代码。
我已经在服务器上启用了一些缓存,并且在浏览器中文件加载非常快。但是,从我的应用程序中需要更长的时间(比如30秒以上),即使在很好的连接上。我已经在我的服务器上启用了GZIP,并且使浏览器更快加载(< 1秒)。不过,我的应用程序仍然很慢。考虑到这种情况发生在应用程序的第一次启动时,需要等待很长时间才是非常糟糕的体验。
我能做些什么来加速这个过程从应用程序?
在此先感谢
(下面的代码)
private class DownloadData extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String result = "";
try {
// Create a URL for the desired page
URL url = new URL("LINK HERE");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
result += str;
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
return result;
}
@Override
protected void onPostExecute(String result) {
// Result processed here. It takes 30 seconds to reach this point, so no delay is happening here
}
@Override
protected void onPreExecute() {
// Some UI Things
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
This while循环让你的下载速度变慢:'while((str = in.readLine())!= null){ result + = str; }'通过应用'byte [] buffer = new byte [1024];'并读取尽可能多的字节,将解决这个问题。相应地调整缓冲区大小 –
有趣的是,我会尽快尝试。如果这能解决它,我会让你知道,这样我就可以将答案标记为已完成。谢谢参观。 –