我有两个AsyncTask,一个用于下载xml文件(DownloadTask),另一个用于解析文件(ParseXMLTask)。使用此任务有两种情况:
1) 文件不存在 > 执行 DownloadTask, onPostExecute > ParseXMLTask
2) 文件存在 > 只执行 ParseXMLTask。
一切正常,但问题是,在执行第二种情况时,用户界面会阻塞大约 3 秒(黑屏),这肯定会让用户感到恼火。这绝对让我感到困惑,因为第二种情况下的工作似乎更容易。
所以当我在测试我的应用程序时,情况是这样的:我第一次点击按钮,正在下载文件,保存在 sd 卡上,解析并最终打开。然后我返回并再次单击该按钮。现在我看到了在活动之间切换时的滞后。
代码:
执行任务
private void downloadPack() {
if (packDownloaded) {
parseXML();
} else {
download = new DownloadFile(fileName, this, loadingBar);
download.execute(serverURL + fileName + ".xml");
}
}
private void parseXML() {
ParseXMLTask parseTask = new ParseXMLTask(this, this);
parseTask.execute(PATH + fileName + ".xml");
}
public void postDownload(File result) {
parseXML();
}
public void postParse() {
Intent packIntent = new Intent(this, PackActivity.class);
startActivity(packIntent);
}
ParseXMLTask.java
public class ParseXMLTask extends AsyncTask<String, Integer, Void> {
private Context context;
private XmlPullParser xpp;
private IPostParse iPostParse;
public ParseXMLTask(Context context, IPostParse iPostParse) {
this.context = context;
this.iPostParse = iPostParse;
}
@Override
protected Void doInBackground(String... params) {
File file = new File(params[0]);
/* doing the job */
}
@Override
protected void onPostExecute(Intent result) {
iPostParse.postParse(result);
}
}
下载文件.java
public class DownloadFile extends AsyncTask<String, Integer, File> {
private static final String PATH = Environment
.getExternalStorageDirectory().getPath() + "/.chgkgame/";;
private File dir;
private ProgressBar progressBar;
private String fileName;
private IPostDownload postDownload;
private boolean download;
public DownloadFile(String name, IPostDownload pDownload, ProgressBar pBar) {
progressBar = pBar;
fileName = name;
postDownload = pDownload;
}
@Override
protected File doInBackground(String... sUrl) {
URL url;
try {
url = new URL(sUrl[0]);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int fileLength = urlConnection.getContentLength();
dir = new File(PATH + fileName + ".xml");
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(dir);
byte[] data = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return dir;
}
@Override
protected void onPostExecute(File result) {
if (postDownload != null) postDownload.postDownload(result);
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (progressBar != null) {
progressBar.setProgress(values[0]);
}
}
}