简体   繁体   English

如何检测整个图像已在Android中下载

[英]How to detect that whole image was downloaded in Android

I download images into my android application with this code: 我使用以下代码将图像下载到我的android应用程序中:

private void download(URL url, File file) throws IOException {
    Log.d(TAG, "download(): downloading file: " + url);

    URLConnection urlConnection = url.openConnection();
    InputStream inputStream = urlConnection.getInputStream();
    BufferedInputStream bufferStream;
    OutputStream outputStream = null;
    try {
        bufferStream = new BufferedInputStream(inputStream, 512);
        outputStream = new FileOutputStream(file);
        byte[] buffer = new byte[512];
        int current;
        while ((current = bufferStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, current);
        }
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
        if (inputStream != null) {
            inputStream.close();
        }
    }
}

This code works fine, but some users and testers complained about incomplete photos. 这段代码可以正常工作,但是一些用户和测试人员抱怨照片不完整。 I suspect small network lags which interrupt connection. 我怀疑小型网络滞后会中断连接。 So I would like to detect if whole image was downloaded and saved file is complete image. 因此,我想检测整个图像是否已下载并且保存的文件是否为完整图像。 Is there any way how to detect file size from BufferedInputStream or is there another way how detect download completion? 有什么方法可以检测BufferedInputStream的文件大小,或者有什么方法可以检测下载是否完成?

I suggest using Google Volley which provides a super simple interface for networking in general, and image loading specifically. 我建议使用Google Volley ,它为一般的联网和特定的图像加载提供了一个超级简单的界面。 It takes care of threading and batching for you. 它为您处理线程和批处理。

It's what Google use on the Google Play app. 这就是Google在Google Play应用中使用的方式。

It will solve your problem by providing listeners that notify you when the job is complete. 通过提供在工作完成时通知您的侦听器,它将解决您的问题。

Try something like this . 尝试一些像这样 I think it could help you. 我认为它可以帮助您。

If you are downloading an ordinary file over HTTP, the method getContentLength() of URLConnection gives you the length that the file should have in the end. 如果要通过HTTP下载普​​通文件,则URLConnection的getContentLength()方法将为您提供文件末尾的长度。

You can compare the returned value of this method to the file length/length of downloaded data. 您可以将此方法的返回值与文件长度/下载数据的长度进行比较。 If it's equal, then the file is complete: 如果相等,则文件完成:

int contentLength = urlConnection.getContentLength();
if (contentLength != -1) {
    if (contentLength == file.length()) {
        System.out.println("file is complete");
    } else {
        System.out.println("file is incomplete");
    }
} else {
    System.out.println("unknown if file is complete");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM