2013-03-04 41 views
0

我的應用程序中有一個AsyncTask處理對話框。 Im取消對話任務時取消了背景任務,但它沒有取消任務,但對話框消失了。這裏是代碼在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; 
      //} 
     } 
+0

你是如何確保AsycTask不會被取消? – 2013-03-04 06:48:04

+0

也使用'connection.disconnect();'在調用'dm.cancel(true)前取消http請求''在AsyncTask取消時停止AsyncTask或使用布爾標誌來控制doInBackground執行 – 2013-03-04 06:48:48

+0

@Drax我可以看到我的運行任務在Logcat取消後。 – 2013-03-04 06:52:52

回答

2

你可以把一個變量在這個循環while (downloaded < length)isRunning

,它會變成這個樣子

while (downloaded < length && isRunning) 

默認isRunning = true但是當你取消任務,然後使其false在這種方法

protected void onCancelled() { 

      isRunning = false; 

      } 

你也可以把if聲明while bock like this

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