android asynctask上传多个文件到dropbox

标签 android upload android-asynctask

我想将 SD 中的多个文件上传到 dropbox 文件夹。但问题不在于保管箱问题:

我有一个文件数组,我想逐个上传文件,而不是同时上传所有文件。

上传工作正常,因为我对文件数组进行了 for 循环,但它们是同时执行的。

我想在进度对话框中提供有关文件总大小和数量的信息

有什么建议吗?

谢谢

我从我的类(class)通过:

   Log.i("toBeUploaded",
                                " " + Arrays.toString(toBeUploaded));

                        for (int i = 0; i < toBeUploaded.length; i++) {

                            Upload upload = new Upload(CalcDBActivity.this,
                                    mDBApi, getIntent().getExtras()
                                            .getString("project")
                                            + File.separatorChar,
                                    toBeUploaded[i]);
                            upload.execute();

                            if (upload.getStatus() == Upload.Status.PENDING) {
                                // My AsyncTask has not started yet
                                Log.i("Status pend",
                                        " " + upload.getStatus());
                            }

                            if (upload.getStatus() == Upload.Status.RUNNING) {
                                // My AsyncTask is currently doing work in
                                // doInBackground()
                                Log.i("Status run ",
                                        " " + upload.getStatus());
                            }

                            if (upload.getStatus() == Upload.Status.FINISHED) {
                                Log.i("Status Finished",
                                        " " + upload.getStatus());
                                // My AsyncTask is done and onPostExecute
                                // was called
                            }

                        }

其中“toBeUploaded”是文件数组。

上传类:

public class Upload extends AsyncTask<Void, Long, Boolean> {

private DropboxAPI<?> mApi;
private String mPath;
private File mFile;

private long mFileLen;
private UploadRequest mRequest;
private Context mContext;
private final ProgressDialog mDialog;

private String mErrorMsg;


public Upload(Context context, DropboxAPI<?> api, String dropboxPath,
        File file) {
    // We set the context this way so we don't accidentally leak activities
    mContext = context.getApplicationContext();

    mFileLen = file.length();
    mApi = api;
    mPath = dropboxPath;
    mFile = file;

    mDialog = new ProgressDialog(context);
    mDialog.setMax(100);
    mDialog.setMessage("Uploading " + file.getName());
    mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mDialog.setProgress(0);
    mDialog.setButton("Cancel", new OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // This will cancel the putFile operation
            mRequest.abort();
        }
    });
    mDialog.show();
}

@Override
protected Boolean doInBackground(Void... params) {
    try {
        // By creating a request, we get a handle to the putFile operation,
        // so we can cancel it later if we want to
        FileInputStream fis = new FileInputStream(mFile);
        String path = mPath + mFile.getName();
        mRequest = mApi.putFileOverwriteRequest(path, fis, mFile.length(),
                new ProgressListener() {
            @Override
            public long progressInterval() {
                // Update the progress bar every half-second or so
                return 500;
            }

            @Override
            public void onProgress(long bytes, long total) {
                publishProgress(bytes);
            }
        });

        if (mRequest != null) {
            mRequest.upload();
            return true;
        }

    } catch (DropboxUnlinkedException e) {
        // This session wasn't authenticated properly or user unlinked
        mErrorMsg = "This app wasn't authenticated properly.";
    } catch (DropboxFileSizeException e) {
        // File size too big to upload via the API
        mErrorMsg = "This file is too big to upload";
    } catch (DropboxPartialFileException e) {
        // We canceled the operation
        mErrorMsg = "Upload canceled";
    } catch (DropboxServerException e) {
        // Server-side exception.  These are examples of what could happen,
        // but we don't do anything special with them here.
        if (e.error == DropboxServerException._401_UNAUTHORIZED) {
            // Unauthorized, so we should unlink them.  You may want to
            // automatically log the user out in this case.
        } else if (e.error == DropboxServerException._403_FORBIDDEN) {
            // Not allowed to access this
        } else if (e.error == DropboxServerException._404_NOT_FOUND) {
            // path not found (or if it was the thumbnail, can't be
            // thumbnailed)
        } else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
            // user is over quota
        } else {
            // Something else
        }
        // This gets the Dropbox error, translated into the user's language
        mErrorMsg = e.body.userError;
        if (mErrorMsg == null) {
            mErrorMsg = e.body.error;
        }
    } catch (DropboxIOException e) {
        // Happens all the time, probably want to retry automatically.
        mErrorMsg = "Network error.  Try again.";
    } catch (DropboxParseException e) {
        // Probably due to Dropbox server restarting, should retry
        mErrorMsg = "Dropbox error.  Try again.";
    } catch (DropboxException e) {
        // Unknown error
        mErrorMsg = "Unknown error.  Try again.";
    } catch (FileNotFoundException e) {
    }
    return false;
}

@Override
protected void onProgressUpdate(Long... progress) {
    int percent = (int)(100.0*(double)progress[0]/mFileLen + 0.5);
    mDialog.setProgress(percent);
}

@Override
protected void onPostExecute(Boolean result) {
    mDialog.dismiss();
    if (result) {
        showToast("Image successfully uploaded");
    } else {
        showToast(mErrorMsg);
    }
}

private void showToast(String msg) {
    Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
    error.show();
}

}

最佳答案

将 for 循环移到主类中:

Log.i("toBeUploaded", " " + Arrays.toString(toBeUploaded));

Upload upload = new Upload(CalcDBActivity.this,
    mDBApi,
    getIntent().getExtras().getString("project") + File.separatorChar,
    toBeUploaded);
upload.execute();

进入上传类:

    public class Upload extends AsyncTask<Void, Long, Boolean> {

    private DropboxAPI<?> mApi;
    private String mPath;

    private UploadRequest mRequest;
    private Context mContext;
    private ProgressDialog mDialog;

    private String mErrorMsg;

    //new class variables:
    private int mFilesUploaded;
    private File[] mFilesToUpload;
    private int mCurrentFileIndex;

    public Upload(Context context, DropboxAPI<?> api, String dropboxPath, File[] filesToUpload) {
        // We set the context this way so we don't accidentally leak activities
        mContext = context.getApplicationContext();
        mApi = api;
        mPath = dropboxPath;

        //set number of files uploaded to zero.
        mFilesUploaded = 0;
        mFilesToUpload = filesToUpload;
        mCurrentFileIndex = 0;

        mDialog = new ProgressDialog(context);
        mDialog.setMax(100);
        mDialog.setMessage("Uploading file 1 / " + filesToUpload.length);
        mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mDialog.setProgress(0);
        mDialog.setButton("Cancel", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                cancel(true);
            }
        });
        mDialog.show();
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            for (int i = 0; i < mToBeUploaded.length; i++) {
                mCurrentFileIndex = i;
                File file = mToBeUploaded[i];

                // By creating a request, we get a handle to the putFile operation,
                // so we can cancel it later if we want to
                FileInputStream fis = new FileInputStream(file);
                String path = mPath + file.getName();
                mRequest = mApi.putFileOverwriteRequest(path, fis, file.length(),
                        new ProgressListener() {
                    @Override
                    public long progressInterval() {
                         // Update the progress bar every half-second or so
                         return 500;
                    }

                    @Override
                    public void onProgress(long bytes, long total) {
                        if(isCancelled()) {
                            // This will cancel the putFile operation
                            mRequest.abort();
                        }
                        else {
                            publishProgress(bytes);
                        }
                    }
                });

                mRequest.upload();

                if(!isCancelled) {
                    mFilesUploaded++;
                }
                else {
                    return false;
                }
            }
            return true;
        } catch (DropboxUnlinkedException e) {
            // This session wasn't authenticated properly or user unlinked
            mErrorMsg = "This app wasn't authenticated properly.";
        } catch (DropboxFileSizeException e) {
            // File size too big to upload via the API
            mErrorMsg = "This file is too big to upload";
        } catch (DropboxPartialFileException e) {
            // We canceled the operation
            mErrorMsg = "Upload canceled";
        } catch (DropboxServerException e) {
            // Server-side exception.  These are examples of what could happen,
            // but we don't do anything special with them here.
            if (e.error == DropboxServerException._401_UNAUTHORIZED) {
                // Unauthorized, so we should unlink them.  You may want to
                // automatically log the user out in this case.
            } else if (e.error == DropboxServerException._403_FORBIDDEN) {
                // Not allowed to access this
            } else if (e.error == DropboxServerException._404_NOT_FOUND) {
                // path not found (or if it was the thumbnail, can't be
                // thumbnailed)
            } else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
                // user is over quota
            } else {
                // Something else
            }
            // This gets the Dropbox error, translated into the user's language
            mErrorMsg = e.body.userError;
            if (mErrorMsg == null) {
                mErrorMsg = e.body.error;
            }
        } catch (DropboxIOException e) {
            // Happens all the time, probably want to retry automatically.
            mErrorMsg = "Network error.  Try again.";
        } catch (DropboxParseException e) {
            // Probably due to Dropbox server restarting, should retry
            mErrorMsg = "Dropbox error.  Try again.";
        } catch (DropboxException e) {
            // Unknown error
            mErrorMsg = "Unknown error.  Try again.";
        } catch (FileNotFoundException e) {
        }
        return false;
    }

    @Override
    protected void onProgressUpdate(Long... progress) {
        Long totalBytes = 0;
        Long bytesUploaded = 0;
        for(int i=0;i<mFilesToUpload.length;i++) {
            Long bytes = mFilesToUpload[i].length()
            totalBytes += bytes;

            if(i < mCurrentFileIndex) {
                bytesUploaded += bytes;
            }
        }
        bytesUploaded += progress[0];

        mDialog.setMessage("Uploading file " + (mCurrentFileIndex+1) + " / " + filesToUpload.length);
        mDialog.setProgress((bytesUploaded / totalBytes) * 100);
    }

    @Override
    protected void onPostExecute(Boolean result) {
        mDialog.dismiss();
        if (result) {
            showToast("Image successfully uploaded");
        } else {
            showToast(mErrorMsg);
        }
    }

    private void showToast(String msg) {
        Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
        error.show();
    }
}

关于android asynctask上传多个文件到dropbox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12726498/

相关文章:

android - Asynctask .get() 奇怪的行为

java - 发生异常: android. os.NetworkOnMainThreadException

java - Android 加密不起作用(使用 AES/CBC/PKCS7Padding 的 PBKDF2WithHmacSHA256 加密)

android - 多个广播接收器在android中合法吗?

asp.net-mvc - asp mvc 文件上传(带验证)

php - 不使用生产服务器直接上传到 s3

android - 我怎样才能将 picasso 插入适配器

android - Recycler查看特定单元格无法点击

java - 用于上传大文件的现成 Java 小部件

android - 一个 AsyncTask 用于多个 Activity