如何在Android SDK上使用AWS S3 PersistableDownload

时间:2014-09-22 15:01:39

标签: android amazon-web-services amazon-s3 persistence

有没有人能够在AWS Android SDK上使用PersistableDownload?当应用程序崩溃时,我一直试图用它来恢复下载,但到目前为止还没有成功。我不认为我正确地将序列化/反序列化概念正确化了。这是我到目前为止的代码:

AmazonS3Client s3Client = getAmazonS3Client(Regions.SA_EAST_1);
TransferManager tx = new TransferManager(s3Client);

String bucket = "MyBucket";
String key = "IMG_20140915_132548.jpg";
String[] parts = key.split("/");
String fileName = parts[parts.length - 1];

final String full_path = "/storage/sdcard0/" + fileName;
File file = new File(full_path);
FileInputStream fis = null;
if(file.exists()) {
    try {
        fis = new FileInputStream(file);
        PersistableDownload persistableUpload = PersistableTransfer.deserializeFrom(fis); 
        Download meuDown = tx.resumeDownload(persistableUpload);
    } catch (Exception e1) {
        e1.printStackTrace();
    }
}
else {
    GetObjectRequest getRequest = new GetObjectRequest(bucket, "IMG_20140915_132548.jpg");
    Download download = tx.download(getRequest, file, new S3ProgressListener() {
        @Override
        public void progressChanged(ProgressEvent arg0) {
            long transferred = arg0.getBytesTransferred();
            Log.d("AWS3", "" + transferred);
        }
        @Override
        public void onPersistableTransfer(PersistableTransfer arg0) {
            Log.d("AWS3", "Writing to file");
            File f = new File("/storage/sdcard0/resume-upload");
                FileOutputStream fos;
            try {
                if (f.exists() == false) 
                    f.createNewFile();
                fos = new FileOutputStream(f);
                arg0.serialize(fos);
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

我注意到onPersistableTransfer方法只调用一次,所以我不知道所有接收的字节是如何序列化到磁盘的。

有关如何使PersistableDownload工作的任何建议?我使用SDK 2.1,使用真正的手机(Android 4.4.4)和Eclipse。

1 个答案:

答案 0 :(得分:1)

从上面的代码中,我看到您正在传递部分下载的图像文件以恢复下载过程。

if(file.exists()) {
    try {
        fis = new FileInputStream(file);
        PersistableDownload persistableUpload = PersistableTransfer.deserializeFrom(fis); 
        Download meuDown = tx.resumeDownload(persistableUpload);
    } catch (Exception e1) {
        e1.printStackTrace();
    }
} 

此处文件指的是部分下载的图像文件。您需要传递文件" / storage / sdcard0 / resume-upload"恢复上传。