我正在开发一个必须从互联网上下载一些文件的项目,所有文件下载都很好,但是如果我在下载完成后直接打开下载的文件,我会得到未完成的文件。例如I got only half of the image, but if i wait a little more time, it's open correctly
。
这是我的功能:
private boolean downloadFile(long id, String file_id,
String file_name, boolean full) {
currentFile = id;
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
WakeLock mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
String _para = "?id=" + file_id + "&f=" + (full ? "1" : "0");
URL url = new URL(Server.DOWNLOAD + _para);
if (full)
if (cancel) {
if (mWakeLock.isHeld())
mWakeLock.release();
currentFile = 0;
return false;
}
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (full)
if (cancel) {
if (mWakeLock.isHeld())
mWakeLock.release();
currentFile = 0;
return false;
}
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
if (mWakeLock.isHeld())
mWakeLock.release();
currentFile = 0;
return false;
}
// file size
int file_size = connection.getContentLength();
// download the file
input = connection.getInputStream();
String path = DIR.DIR_THUMB + file_name;
if (full)
if (file_name.startsWith(Media.SMEDIA_TYPE_IMAGE))
path = DIR.DIR_IMAGES + file_name;
else if (file_name.startsWith(Files.S_TYPE_FILE))
path = DIR.DIR_FILES + file_name;
output = new FileOutputStream(path);
byte data[] = new byte[4096];
int count;
int downloaded = 0;
while ((count = input.read(data)) != -1) {
if (full)
if (cancel)
break;
output.write(data, 0, count);
if (full)
if (cancel)
break;
downloaded += count;
if (full)
if (file_size == -1)
progress.onUpdate(id, 0);
else {
progress.onUpdate(
id,
(int) (((float) downloaded / (float) file_size) * 100));
}
}
//edit
output.flush();
if (full)
if (cancel) {
if (mWakeLock.isHeld())
mWakeLock.release();
currentFile = 0;
try {
if (output != null)
output.close();
} catch (IOException ignored) {
}
try {
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
return false;
}
} catch (Exception e) {
if (mWakeLock.isHeld())
mWakeLock.release();
currentFile = 0;
return false;
} finally {
try {
if (output != null)
output.close();
} catch (IOException ignored) {
}
try {
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
if (mWakeLock.isHeld())
mWakeLock.release();
}
if (mWakeLock.isHeld())
mWakeLock.release();
currentFile = 0;
return true;
}
我允许用户在true
返回后打开文件
问题是
我怎么知道文件何时完全写入SD卡?
修改
下载完成后我直接打开下载的文件,我得到了:
incompletely image
我等了一会儿,我得到了:
completed image