【问题标题】:Android show download progress after finishing activity完成活动后Android显示下载进度
【发布时间】:2015-11-08 12:32:41
【问题描述】:
您好,在我的聊天应用程序中,我一直在从 listview 下载媒体文件。我曾使用tad 进行下载操作。当我们停留在同一个活动中时,它工作正常并显示进度状态。如果我们完成了活动并再次来,我怎么能显示从最后一个位置下载的进度。我可以看到在后台进行下载,但我需要在 UI 中显示该状态.. 线程是否可能..我需要使用任何其他方法..?
我已经尝试过使用普通线程..Asynchtask 是否可以完成需要..?
【问题讨论】:
标签:
multithreading
android-activity
android-asynctask
android-progressbar
activity-finish
【解决方案1】:
This is my thread
@Override
public void run() {
try {
URL url = new URL(task.url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(1000);
connection.setReadTimeout(1000);
if (chunk.end != 0) // support unresumable links
connection.setRequestProperty("Range", "bytes=" + chunk.begin + "-" + chunk.end);
connection.connect();
File cf = new File(FileUtils.address(task.save_address, String.valueOf(chunk.id)));
InputStream remoteFileIn = connection.getInputStream();
FileOutputStream chunkFile = new FileOutputStream(cf, true);
int len = 0;
// set watchDoger to stop thread after 1sec if no connection lost
watchDog = new ConnectionWatchDog(5000, this);
watchDog.start();
while (!this.isInterrupted() &&
(len = remoteFileIn.read(buffer)) > 0) {
watchDog.reset();
chunkFile.write(buffer, 0, len);
process(len);
}
chunkFile.flush();
chunkFile.close();
watchDog.interrupt();
connection.disconnect();
if (!this.isInterrupted()) {
observer.rebuild(chunk);
}
}catch (SocketTimeoutException e) {
e.printStackTrace();
observer.connectionLost(task.id);
puaseRelatedTask();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return;
}
process(len) will send progress status to the UI using interface callbacks.