从Android缓慢上传文件到Amazon S3

时间:2015-07-03 08:59:55

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

我已按照亚马逊指南将文件上传到Amazon S3,我注意到它太慢了。上传20kb左右的简单png文件大约需要10秒。

最初我认为问题与线程有关,我已经实现了AsyncTask来上传图像,但问题仍然存在。以下是用于上传图像的代码。

private class UploadFileTask extends AsyncTask<String, Integer, String> {
    String remotePath;
    String remoteFileName;
    File file;
    Context context;
    S3UploadInterface listener;


    public UploadFileTask(Context context,String remotePath,String remoteFileName, File file, S3UploadInterface listener){
        this.context=context;
        this.remotePath=remotePath;
        this.remoteFileName=remoteFileName;
        this.file=file;
        this.listener=listener;
    }

    protected String doInBackground(String... params) {
        credentialsProvider = new CognitoCachingCredentialsProvider(context,
                "MY_PRIVATE_CREDENTIAL",
                Regions.US_EAST_1);
        TransferManager transferManager = new TransferManager(credentialsProvider);
        Upload upload = transferManager.upload(remotePath, remoteFileName, file);
        TransferProgress transferred = upload.getProgress();
        while (!upload.isDone()) {
            try {
                publishProgress((int) transferred.getPercentTransferred());
            } catch (Exception e) {
                listener.uploadFailed(e);
            }
        }
        return "uploaded";
    }

    protected void onProgressUpdate(Integer... progress) {
        if (listener!=null)
            listener.currentUploadProgress(progress[0]);
    }

    protected void onPostExecute(String result) {
        if (listener!=null)
            listener.uploadCompleted();
    }
}

有什么想法解决这个问题吗? 谢谢:))

1 个答案:

答案 0 :(得分:4)

这会打击你的CPU

    while (!upload.isDone()) {
        try {
            publishProgress((int) transferred.getPercentTransferred());
        } catch (Exception e) {
            listener.uploadFailed(e);
        }
    }

尝试添加Thread.sleep以使其他线程有时间运行。