elprl
elprl

Reputation: 1960

Cancelling Dropbox getFile download

When using the Android Dropbox SDK, does anyone know of the best way to cancel a download after the getFile call starts. At the moment, my AsyncTask class does the following:

@Override
protected O2ShellFileManagerError doInBackground(File... params) {
    if (params[0] == null) {
        return new O2ShellFileManagerError(
                "No File found.",
                O2ShellErrorCode._o2sfm_ec_unknown);
    }

    File mFile = params[0];

    try {
        DropboxAPI<AndroidAuthSession> mDBApi = O2DropboxStorage
                .getDropboxSession(mContext);

        // mOutputStream is class level field.
        mOutputStream = new FileOutputStream(mFile);
        DropboxFileInfo info = mDBApi.getFile(mDropboxPath, null,
                mOutputStream, new ProgressListener() {

                    @Override
                    public void onProgress(long bytes, long total) {
                        if (!isCancelled())
                            publishProgress(bytes, total);
                        else {
                            if (mOutputStream != null) {
                                try {
                                    mOutputStream.close();
                                } catch (IOException e) {
                                }
                            }
                        }
                    }
                });
    } catch (DropboxException e) {
        Log.e("DbExampleLog",
                "Something went wrong while getting file.");

    } catch (FileNotFoundException e) {
        Log.e("DbExampleLog", "File not found.");

    } finally {
        if (mOutputStream != null) {
            try {
                mOutputStream.close();
                mOutputStream = null;
            } catch (IOException e) {
            }
        }
    }
    /*
     * The task succeeded
     */
    return null;
}

So my workaround above essentially closes the mOutputStream in the OnProgess method which generates the DropboxException. Is there a better / cleaner way than this?

Upvotes: 2

Views: 1462

Answers (1)

Tom Lin
Tom Lin

Reputation: 501

Use the getFileStream API to get DropboxInputStream.

public DropboxAPI.DropboxInputStream getFileStream(java.lang.String path, java.lang.String rev)

When a user cancels the download, call the close function of DropboxInputStream.

I think this method can release the resources totally.

Upvotes: 1

Related Questions