AsyncTask中未取消后台进程

时间:2013-03-04 06:41:23

标签: android android-asynctask android-dialog

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

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

preExecute:

@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);

            }   

Doinbackground:

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;
            //}
        }

2 个答案:

答案 0 :(得分:2)

您可以在此循环中添加变量while (downloaded < length)isRunning

它会变成这样的

 while (downloaded < length && isRunning) 

默认情况下为isRunning = true但是当您取消任务时,请在此方法中将其设为false

protected void onCancelled() {

           isRunning = false;

            } 

此外,您可以在if bock中添加while语句,如下所示

  while (downloaded < length)
  {
   if(!isRunning){
     return null;
    }
   .... your code goes here
  } 

答案 1 :(得分:1)

根据我的观点,这更多的是如何优雅地取消asynctask。所以请参考此链接获取相同的

Android: Cancel Async Task