【问题标题】:Google cloud storage - Download object from Android appGoogle 云存储 - 从 Android 应用下载对象
【发布时间】:2020-04-25 10:36:01
【问题描述】:

我正在编写一个简单的 android 库,它可以下载存储在 地面站。下面的代码工作正常

Storage storage = StorageOptions.newBuilder()
                        .setProjectId(PROJECT_ID)
                        .setCredentials(ServiceAccountCredentials.fromStream(getAssets().open(JSON_CREDENTIAL)))
                        .build()
                        .getService();
            Blob blob = storage.get(BlobId.of(BUCKET_NAME, BLOB_NAME));
            ReadChannel readChannel = blob.reader();
            FileOutputStream fileOutputStream = new FileOutputStream(filePath);
            fileOutputStream.getChannel().transferFrom(readChannel, 0, Long.MAX_VALUE);
            fileOutputStream.close();

1) 但问题是我需要给出下载进度,我找不到上述方法的任何回调?

2) 另外,这是将文件从 GCS 下载到 Android 应用程序的最佳方式吗?我不能使用 firebase,因为此代码存在于库中并被许多客户端应用程序使用,并且 firebase 要求所有客户端应用程序都链接到 firebase 帐户,我不想这样做。

【问题讨论】:

  • 如果您想要进步,请考虑仅读取和写入流,而不是使用transferFrom,它会在一次内部通道之间复制数据。

标签: android google-cloud-storage progress-bar


【解决方案1】:

正如@Doug 所说,使用流可以获得进度条更好。

您的代码将是这样的:

        Storage storage = StorageOptions.newBuilder()
                                .setProjectId(PROJECT_ID)
                                .setCredentials(ServiceAccountCredentials.fromStream(getAssets().open(JSON_CREDENTIAL)))
                                .build()
                                .getService();
        int BUFFER_SIZE = 64 * 1024;
        Blob blob = storage.get(BlobId.of(BUCKET_NAME, BLOB_NAME));
        ReadChannel readChannel = blob.reader();
        byte[] content = null;
        if (blob != null) {
            reader = blob.reader();
            ByteBuffer bytes = ByteBuffer.allocate(BUFFER_SIZE);

            while (reader.read(bytes) > 0) {
                bytes.flip();
                content = ArrayUtils.addAll(content,bytes.array());
                bytes.clear();
                //Here you can add the progress bar logic
            }
        }

        FileOutputStream fileOutputStream = new FileOutputStream(filePath);
        fileOutputStream.write(content);
        fileOutputStream.close();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    相关资源
    最近更新 更多