1

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

                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

4

2 回答 2

2

你似乎错过了如何AsyncTask工作。该onCancelled()方法只会在doInBackground()完成后调用,类似于该onPostExecute()方法。它不会uploadTask.cancel(true)像您想象的那样在被调用后立即调用。您使用它的方式,您不需要onCancelled()方法或isRunning变量(当前在您的代码isRunning中永远不会更改为false,因此您的isCancelled()检查永远不会起作用)。删除onCancelled()方法和isRunning变量,您AsyncTask将工作。

于 2013-10-24T12:16:15.260 回答
0

检查这个,取消异步任务后写这个条件。

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

它可能对你有帮助。:)

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

于 2013-10-24T11:30:23.157 回答