How to stop AsyncTask ? why it does not stop when calling finish method?

1.8k Views Asked by At

In my app I have a progress bar On notification drawer,when user clicks on the notification I call finish method for that activity,but the progress bar is still working .The progress bar is initialised in an AsyncTask in another class .What I need is ,I want to stop the upload progress bar,and Activity when user clicks on the notification.Any help? And my code is.

Progressbar

public void showProgressBar(){
    mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    mBuilder = new NotificationCompat.Builder(ImageUploadActivity.this);
    mBuilder.setContentTitle("Upload")
            .setContentText("Upload in progress")
            .setSmallIcon(R.drawable.ic_launcher);
    Intent myIntent = new Intent(this, ImageUploadActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(ImageUploadActivity.this, 0,   myIntent, Intent.FILL_IN_ACTION);
    // mBuilder.setAutoCancel(true);
    mBuilder.setContentIntent(pendingIntent);
   // myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
    mTask = new ImageUploadTask().execute();
   // new ImageUploadTask().execute();
}

AsyncTask

 class ImageUploadTask extends AsyncTask<Void,Integer, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        // Displays the progress bar for the first time.
        mBuilder.setProgress(100, 0, false);
        mNotifyManager.notify(id, mBuilder.build());



    }
    @Override
    protected void onProgressUpdate(Integer... values) {
        // Update progress
        mBuilder.setProgress(100, values[0], false);
        mNotifyManager.notify(id, mBuilder.build());
        super.onProgressUpdate(values);
    }
    @Override
    protected String doInBackground(Void... unsued) {
        int i;
        for (i = 0; i <= 100; i += 5) {
            // Sets the progress indicator completion percentage
            publishProgress(Math.min(i, 100));
            try {

                Thread.sleep(2 * 1000);
                HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();
                HttpPost httpPost = new HttpPost("http://10.1.1.1/test/upload.php");

                MultipartEntity entity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);

                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                byte[] data = bos.toByteArray();


          /* entity.addPart("uploaded_file", new ByteArrayBody(data,
                    "myImage.jpg"));*/

                // String newFilename= filename.concat("file");
                // newFilename=filename+newFilename;

                entity.addPart("uploaded_file", new ByteArrayBody(data,
                        filename));
                //  Log.e(TAG, "Method invoked");
                httpPost.setEntity(entity);
                HttpResponse response = httpClient.execute(httpPost,
                        localContext);
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(
                                response.getEntity().getContent(), "UTF-8"));

                StringBuilder builder = new StringBuilder();
                String aux = "";

                while ((aux = reader.readLine()) != null) {
                    builder.append(aux);
                }

                String sResponse = builder.toString();


                return sResponse;
            } catch (Exception e) {
             /*   if (dialog.isShowing())
                    dialog.dismiss();
                Toast.makeText(getApplicationContext(), "Exception Message 1", Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
                return null;*/
            }
        }
        return null;
    }


    @Override
    protected void onPostExecute(String result) {


        super.onPostExecute(result);
        mBuilder.setContentText("Upload completed");
        // Removes the progress bar
        mBuilder.setProgress(0, 0, false);
        mNotifyManager.notify(id, mBuilder.build());


    }
 }}

Here I am calling the finish method

Button btnClosePopup = (Button) layout.findViewById(R.id.btn_cancel);

       btnClosePopup.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                mTask.cancel(true);
                ImageUploadActivity.this.finish();
                Toast.makeText(getApplicationContext(),
                        "Upload Cancelled", Toast.LENGTH_SHORT).show();

            }
        });
2

There are 2 best solutions below

5
On BEST ANSWER

A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns.

To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)

Put below code inside loop in doInBackground(Object[]) method.

if (isCancelled()) break;

Please see below link for more details...

http://developer.android.com/reference/android/os/AsyncTask.html

Edit:

 while ((aux = reader.readLine()) != null) {
    builder.append(aux);
    if (isCancelled()) break;
 }
0
On

You can try as below..

  @Override
    protected String doInBackground(Void... unsued) {
        int i;
        for (i = 0; i <= 100; i += 5) {
            // Sets the progress indicator completion percentage

            //add this
            if (isCancelled())
              return null; 

            publishProgress(Math.min(i, 100));

and Override onCancelled like this

  @Override
 protected void onCancelled () 
{
ImageUploadActivity.this.finish();
                Toast.makeText(getApplicationContext(),
                        "Upload Cancelled", Toast.LENGTH_SHORT).show();
}