什么是最有效的方式来下载谷歌硬盘图像在安卓



我正在编写一个应用程序,需要从谷歌驱动器下载图像。我目前正在使用以下代码执行此操作:

protected void downloadFromDrive(Context context) {
    InputStream input = null;
    FileOutputStream output = null;
    try {
        HttpRequest request = GoogleDriveWorker.get(context)
        .getDrive()
        .getRequestFactory()
        .buildGetRequest(new GenericUrl(getUri()));
        input = request.execute().getContent();
        output = context.openFileOutput(getImageFilename(), Context.MODE_PRIVATE);
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];
        int len = 0;
        while ((len = input.read(buffer)) != -1) {
            output.write(buffer, 0, len);
        }
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if(output!=null)
                output.close();
            if(input!=null)
                input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
public String getUri() {
    return mUri;
}

GoogleDriveWorker只是一个类,它获得一个谷歌驱动器与我们正在使用的凭据。无论如何,我能找到的大多数例子都使用这种基本结构从InputStream下载文件并将其放入OutputStream,但下载速度相当慢。

首先,我可以使用比同步缓冲InputStreamOutputStream更复杂的方法来加速它吗?我突然想到,我应该尝试在不同的线程上读取InputStream,并在使用块队列的千字节块可用时输出到OutputStream。将读代码和写代码捆绑在一起似乎很笨拙,而且它们肯定会相互减慢速度。

其次,改变缓冲区大小会影响数据速率吗?1kb看起来很小,但在移动连接上可能不是那么小。然后,数据块越大,读/写循环的每个部分的等待时间就越长。是否值得考虑使用不同大小的缓冲区?

我认为没有比你所做的更复杂的方法了。您可能会对更大的块(例如几百KB)进行一些实验并测量时间。我认为它更快。

还要检查drive/java-api-client-library文档中关于块大小的信息。

最新更新