如何使用Box Api v2取消AsyncTask中的文件下载?

时间:2014-01-06 09:07:06

标签: android box-api

我已经成功地使用进度对话框实现了下载asyntask,但我想允许用户使用Dialog按钮监听器取消下载过程,我遇到的问题是IFileTransferListener显然不会监听此请求和下载线程在调用的asyntask被取消后继续。

获取的错误是:java.lang.IllegalStateException:无法执行任务:任务已在运行。

我试图取消下载请求,有人可以帮助我吗? TIA

这是我的代码:

uploadDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener(){

        @Override
        public void onClick(DialogInterface arg0, int arg1) {
            cancelDownload = true;
            mTask.cancel(true);
        }
    });

protected class downloadTask extends AsyncTask<BoxAndroidFile, Integer, Boolean> {



    @Override
    protected void onPreExecute(){

        uploadDialog.setMessage("Downloading " + mDownloadfile);
        uploadDialog.setCancelable(true);
        cancelDownload = false;
        uploadDialog.show();
    }

    @Override
    protected Boolean doInBackground(BoxAndroidFile... arg0) {

        while(!cancelDownload){

            if(cancelDownload){
                break;
            }

            try {           


                downloadFile(mDownloadfile, arg0[0], IFileTransferListener);
            }
            catch (Exception e) {
                Log.e(TAG, "An error occurred when downloading a file.", e);
                return false;
            }

        }
        return true;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onCancelled(){
        cancelDownload = true;
        this.cancel(true);
        Toast.makeText(FileListActivity.this, "Download canceled!", Toast.LENGTH_SHORT).show();

    }

    @Override
    protected void onPostExecute(Boolean result) {
        uploadDialog.dismiss();
        if (result) {
            Toast.makeText(FileListActivity.this, "Successfully downloaded " + mDownloadfile.getName() + ".", Toast.LENGTH_LONG).show();
        }
        else {
            Toast.makeText(FileListActivity.this, "An error occurred when downloading.", Toast.LENGTH_LONG).show();
        }                
    }

0 个答案:

没有答案