即使使用cancel方法也无法取消AsyncTask中的doInBackground进程

时间:2013-10-24 11:11:58

标签: java android android-asynctask

我已经声明了FileUploadTask的实例,它在onCreate()方法中扩展了AsyncTask

                FileUploadTask uploadTask= null;

并通过以下代码执行后台方法

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

                }

有取消按钮取消后台处理

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


                        }

                }

在FileUploadTask类中声明了一个布尔值来检查运行状态

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

doInBackground方法

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

并重载onCancelled方法

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

        }

我尝试了很多并且进行了探索。即使使用取消方法,我也无法在后台停止上传过程。请任何人给出问题的解决方案 我提到的一些链接

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

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

2 个答案:

答案 0 :(得分:2)

您似乎错过了AsyncTask的工作方式。 onCancelled()方法仅在doInBackground()完成后调用,类似于onPostExecute()方法。调用uploadTask.cancel(true)之后不会立即调用它,因为您认为它会被调用。您使用它的方式,您不需要onCancelled()方法或isRunning变量(当前在您的代码中isRunning永远不会更改为false,因此您的isCancelled() 1}}检查永远不会起作用)。删除onCancelled()方法和isRunning变量,AsyncTask即可。

答案 1 :(得分:0)

检查这个,取消asynctask后写这个条件。

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

它可能对你有所帮助。 :)

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