Android S3 AWS下载 - 完整返回文件上的TransferListener

时间:2017-08-23 13:00:39

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

我正在使用AWS S3,我想在完成进程时返回文件。这是我的代码:

 public static File downloadFile(Context context, String name, String dirPath){
    File dir = new File(dirPath);
    if(!dir.exists())
        dir.mkdirs();
    File file = new File(dirPath, name);
    try
    {
        file.createNewFile();
        FileOutputStream fOut = new FileOutputStream(file);
        fOut.flush();
        fOut.close();
        Toast.makeText(context, "File saved", Toast.LENGTH_LONG).show();

        TransferUtility transferUtility = Util.getTransferUtility(context);
        TransferObserver observer = transferUtility.download(Constants.BUCKET_NAME, name,
                file);

        observer.setTransferListener(new TransferListener() {
            @Override
            public void onStateChanged(int id, TransferState state) {
                Log.e("onStateChanged", state.toString());
                //RETUN FILE ON COMPLETED STATE
            }

            @Override
            public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
            }

            @Override
            public void onError(int id, Exception ex) {
                Log.e("onError", ex.toString());
            }
        });

        return file;
    }
    catch (IOException e)
    {
        Log.e("Exception", "File write failed: " + e.toString());
    }
    return null;

}

我遇到的问题是该函数在传输完成之前返回文件。如何让它等到转移完成?

1 个答案:

答案 0 :(得分:0)

我稍微更改了我的功能,现在,只返回一个文件,我返回一个对象:

public class DownloadDataS3 {
     private File file;
     private TransferObserver observer;
}

然后在活动中我管理观察者。