Karthikeyan Ve
Karthikeyan Ve

Reputation: 2549

Can't cancel doInBackground process in AsyncTask even using cancel method

I have declared instance of FileUploadTask which extends AsyncTask in onCreate() method

                FileUploadTask uploadTask= null;

and executes the background method by following code

                    public class UploadFiles implements OnClickListener{

                    ....

                    if(SOTCNetStat.chkConnectionStatus(UploadResult.this)){
                                uploadTask=new FileUploadTask();
                                uploadTask.execute("");
                            }
                            else
                            {
                                Toast.makeText(UploadResult.this, getResources().getString(R.string.Text_CheckNetworkConnections) , Toast.LENGTH_LONG).show();                              
                            }
                    ....

                }

Having a cancel button to cancel the background process

                cancel.setOnClickListener(new OnClickListener() {
                @Override
                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            Log.d(TAG,"cancel button clicked.....");
                            //FileUploadTask uploadTask= new FileUploadTask();
                            if(uploadTask!=null)
                            {
                                Log.d(TAG,"click event null checking....");
                                uploadTask.cancel(true);
                            }


                        }

                }

In FileUploadTask class declared a boolean to check the running status

        public class FileUploadTask extends AsyncTask<String, Integer, String> {
        ....
            boolean isRunning=true;

The doInBackground method

    @Override
        protected String doInBackground(String... arg0) {

            for(int i=0; i<fp.size(); i++){
                index = i+1;

                if(isCancelled() && !isRunning)
                {
                    Log.d(TAG,"Cancel 1 Condition Checked ["+i+"]");
                    Log.d(TAG,"doInBackground canceled");
                    break;

                }
                else
                {
                    Log.d(TAG,"Cancel 1 Canceled ["+i+"]");
                }

                file1 = new File(fp.get(i));

                String urlString = Constants.UPLOAD_URL;

                try {

                    Log.e("doInBackground", "urlString: " + urlString);

                    Log.e("doInBackground", "domainPref: " + domainName);

                    urlString = urlString.replace("domain", URLEncoder.encode(domainName, "UTF-8"));

                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }




                try {

                    HttpClient client = new DefaultHttpClient();
                    HttpPost post = new HttpPost(urlString);
                    FileBody bin1 = new FileBody(file1);

                    ProgressMultipart reqEntity = new ProgressMultipart(new ProgressListener() {

                        @Override
                        public void transferred(long num) {
                            //publishProgress((int) ((num / (float) file1.length() ) * 100));

                            publishProgress((int) ((num / (float) totalSize ) * 100));
                        }
                    });

                    reqEntity.addPart("userfile", bin1);
                    if(getIntent().hasExtra("show_id"))
                    {
                        //String showId = getIntent().getStringExtra("show_id");
                        reqEntity.addPart("mobileshow", new StringBody("1"));
                        reqEntity.addPart("show_ids", new StringBody(getIntent().getStringExtra("show_id")));
                    }
                    reqEntity.addPart("Filename", new StringBody(file1.getName()));
                    reqEntity.addPart("user_id", new StringBody("2"));
                    reqEntity.addPart("privateasset", new StringBody("true"));
                    reqEntity.addPart("uploadtype", new StringBody("Normal"));
                    reqEntity.addPart("version_num", new StringBody("1"));

                    totalSize = reqEntity.getContentLength();

                    post.setEntity(reqEntity);

                    System.err.println("post :"+post.toString());

                    //to be check the cancel operation
                    if(isCancelled() && !isRunning)
                    {
                        Log.d(TAG,"Cancel 2 Condition Checked ["+i+"]");
                        Log.d(TAG,"File Uploading Cancelled in doInBackground method");
                        break;
                    }
                    else
                    {
                        Log.d(TAG,"Cancel 2 Canceled ["+i+"]");
                    }

                    HttpResponse response = client.execute(post);

                    resEntity = response.getEntity();
                    response_str = EntityUtils.toString(resEntity);
                } 
    ....
    return response_str;
    }

and overloaded onCancelled methods

@Override
        protected void onCancelled() {
            // TODO Auto-generated method stub
            Log.d(TAG,"onCancelled() method called");
            super.onCancelled();

        }

        @Override
        protected void onCancelled(String result) {
            // TODO Auto-generated method stub
            Log.d(TAG,"onCancelled(String) method called");

            isRunning=false;


            this.cancel(true);

        }

I tried a lot and explored . Even using cancel method I can't able to stop the uploading process in background. Please any one give solutions to the problem Some links i referred

http://www.technotalkative.com/cancel-asynctask-in-android/

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

Upvotes: 1

Views: 2123

Answers (2)

Piovezan
Piovezan

Reputation: 3223

You seem to be missing how AsyncTask works. The onCancelled() method will only be called after doInBackground() is finished, similar to the onPostExecute() method. It is not called immediately after uploadTask.cancel(true) is called as you think it will be. The way you are using it, you have no need for onCancelled() methods or an isRunning variable (currently in your code isRunning is never changed to false and thus your isCancelled() check never works). Remove both the onCancelled() methods and the isRunning variable and your AsyncTask will work.

Upvotes: 2

balaji koduri
balaji koduri

Reputation: 1321

check this, after canceling the asynctask write this condition.

if(asynctask.iscancel()){
break;
}

it may help for u. :)

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

Upvotes: 0

Related Questions