0

我的应用程序中有一个带有处理对话框的 AsyncTask 。我在关闭对话框时取消后台任务,但它没有取消任务但对话框消失。这是代码

DownloadImageTask dm = null;//new DownloadImageTask();
dm = new DownloadImageTask();
         dm.execute();

预执行:

@Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            pd = new ProgressDialog(Tab_book.this);
            pd.setTitle("Loading Images..");
            pd.setMessage("Please wait...");
            pd.setCancelable(true);

            pd.show();
            pd.setOnCancelListener(new DialogInterface.OnCancelListener(){
                  public void onCancel(DialogInterface dialog) {
                      dm.cancel(true);
                      //finish();
                  }
            });

        }

取消方法:

protected void onCancelled() {

            cancel(true);

            }   

做背景:

protected Bitmap doInBackground(Void... params) {

            int j = 0;// List.size();
            try {
                for (; j < List.size(); j++) {
                    reviewImageLink = List.get(j).get(TAG_Image);
                    URL url = new URL(reviewImageLink);
                    // URL reviewImageURL;
                    String name = reviewImageLink.substring(reviewImageLink.lastIndexOf("/") + 1,reviewImageLink.length());
                    if (!hasExternalStoragePublicPicture(name)) {
                        isImage = false;
                        Log.v("log_tag", "if");
                        isImage = true;
                        File sdImageMainDirectory = new File(Environment.getExternalStorageDirectory(),getResources().getString(R.string.directory_book));
                        // if(!sdImageMainDirectory.exists()){
                        sdImageMainDirectory.mkdirs();
                        File file = new File(sdImageMainDirectory, name);
                        Log.v("log_tag", "Directory created");
                    }
                    HttpURLConnection connection = (HttpURLConnection) url
                            .openConnection();
                    int length = connection.getContentLength();
                    InputStream is = (InputStream) url.getContent();
                    byte[] imageData = new byte[length];
                    int buffersize = (int) Math.ceil(length / (double) 100);
                    int downloaded = 0;
                    int read;
                    while (downloaded < length) {
                        if (length < buffersize) {
                            read = is.read(imageData, downloaded, length);
                        } else if ((length - downloaded) <= buffersize) {
                            read = is.read(imageData, downloaded, length
                                    - downloaded);
                        } else {
                            read = is.read(imageData, downloaded, buffersize);
                        }
                        downloaded += read;
                        setProgress((downloaded * 100) / length);

                    }
                    Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0,
                            length);
                    if (bitmap != null) {
                        Log.i(TAG, "Bitmap created");
                    } else {
                        Log.i(TAG, "Bitmap not created");
                    }
                    is.close();
                    saveToSDCard(bitmap, name);
                }//

                images();

            } catch (MalformedURLException e) {
                Log.e(TAG, "Malformed exception: " + e.toString());

            } catch (IOException e) {
                Log.e(TAG, "IOException: " + e.toString());
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.toString());
            }
            finally{
                Log.v("tag", "try again ");
            }
    //      }
            // Bitmap b=images.get(j);
            return null;
            //}
        }
4

2 回答 2

2

你可以在这个循环中放一个变量while (downloaded < length)isRunning

它会变成这样

 while (downloaded < length && isRunning) 

默认情况下isRunning = true ,但是当您取消任务时false,请使用此方法

protected void onCancelled() {

           isRunning = false;

            } 

你也可以像这样if在里面写一个声明while

  while (downloaded < length)
  {
   if(!isRunning){
     return null;
    }
   .... your code goes here
  } 
于 2013-03-04T06:52:40.293 回答
1

根据我的观点,这更多的是如何优雅地取消 asyctask。所以请参考这个链接

Android:取消异步任务

于 2013-03-04T06:55:25.437 回答