簡體   English   中英

即使使用cancel方法也無法取消AsyncTask中的doInBackground進程

[英]Can't cancel doInBackground process in AsyncTask even using cancel method

我已經聲明了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

您似乎缺少AsyncTask工作方式。 所述onCancelled()方法將只是之后調用doInBackground()完成后,類似於onPostExecute()方法。 您不會uploadTask.cancel(true)那樣立即調用uploadTask.cancel(true)之后立即調用它。 使用它的方式,不需要onCancelled()方法或isRunning變量(當前在您的代碼中, isRunning從未更改為false ,因此isCancelled()檢查永遠isCancelled() )。 刪除onCancelled()方法和isRunning變量,您的AsyncTask將起作用。

取消asynctask后,請檢查此條件,並寫下此條件。

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

它可能對你有幫助。 :)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM