0

I have a AsyncTask in my application with a processing dialog . Im cancelling back ground task on dismiss of dialog but its did not cancel the task but dialog disappear . here is code

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();
                  }
            });

        }

Cancel method:

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;
            //}
        }
Bibi Tahira
  • 1,082
  • 5
  • 15
  • 39

2 Answers2

2

You can put a variable in this loop while (downloaded < length) say isRunning

and it will become like this

 while (downloaded < length && isRunning) 

by default isRunning = true but when you cancel the task then make it false in the this method

protected void onCancelled() {

           isRunning = false;

            } 

Also you can put a if statement in the while bock like this

  while (downloaded < length)
  {
   if(!isRunning){
     return null;
    }
   .... your code goes here
  } 
Ali Imran
  • 8,927
  • 3
  • 39
  • 50
1

According to my opinion this is more of how to cancel the asyctask gracefully. so please refer this link for the same

Android: Cancel Async Task

Community
  • 1
  • 1
Dinesh Prajapati
  • 9,274
  • 5
  • 30
  • 47