我的Android AsyncTask在取消时仍然运行,如何解决?

时间:2014-11-17 07:04:09

标签: java android android-asynctask

在我的应用程序中实现Asynctask,但我的AsyncTask在取消时仍然运行而不是停止。那怎么解决呢?这是我的代码

我跑的时候

myTask = new ImageUploadTask();
myTask.execute();

这个Asyntask

class ImageUploadTask extends AsyncTask <Void, Void, String>{
            String err=null;
            @Override
            protected String doInBackground(Void... unsued) {
                 for(int i = 0; i <= 30000; i++) {
                        if(myTask.isCancelled()) break;
                    }

                try {

                    ByteArrayOutputStream bos_1 = new ByteArrayOutputStream();
                    bitmap_photo_1.compress(CompressFormat.JPEG, 100, bos_1);
                    byte[] data_1 = bos_1.toByteArray();

                    HttpParams httpParameters = new BasicHttpParams();
                    // Set the timeout in milliseconds until a connection is established.
                    int timeoutConnection = 30*1000;
                    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
                    // Set the default socket timeout (SO_TIMEOUT) 
                    // in milliseconds which is the timeout for waiting for data.
                    int timeoutSocket = 30*1000;
                    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

                    HttpClient httpClient = new DefaultHttpClient(httpParameters);              
                    HttpPost postRequest = new HttpPost(Variabel.URL_CONFIRM_ACTION);               
                    ByteArrayBody bab_1 = new ByteArrayBody(data_1,var_photo_1);                
                    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

                    reqEntity.addPart(Variabel.KEY_USER_ID, new StringBody(Variabel.user_id.toString().trim()));
                    reqEntity.addPart(Variabel.KEY_PHOTO_1, bab_1);
                    reqEntity.addPart(Variabel.KEY_PHOTO_1_TIME, new StringBody(var_photo_1_time.toString().trim()));
                    reqEntity.addPart(Variabel.KEY_PHOTO_1_LOCATION_LONGITUDE, new StringBody(var_photo_1_location_longitude.toString().trim()));
                    reqEntity.addPart(Variabel.KEY_PHOTO_1_LOCATION_LATITUDE, new StringBody(var_photo_1_location_latitude.toString().trim()));

                    postRequest.setEntity(reqEntity);
                    HttpResponse response = httpClient.execute(postRequest);
                    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),"UTF-8"));
                    String sResponse;
                    StringBuilder s = new StringBuilder();

                    while ((sResponse = reader.readLine()) != null) {
                        s = s.append(sResponse);
                    }

                    return s.toString().trim();

                } catch (Exception e) {

                    err="error"+e.getMessage();
                    Log.e(e.getClass().getName(), e.getMessage());

                    return e.getMessage();
                }       

            }

取消代码

myTask.cancel(true);  

那么如何完全停止? 对不起我的英文

1 个答案:

答案 0 :(得分:0)

你不能立即杀死asynctask。为了停止你应该先取消它:

task.cancel(true);

并且在asynctask的doInBackground()方法中检查它是否已被取消:

isCancelled()

如果是,请手动停止执行。

偶尔检查isCancelled():

 protected Object doInBackground(Object... x) {
    while (/* condition */) {
      // work...
      if (isCancelled()) break;
    }
    return null;
 }