如何停止 AsyncTask ?为什么在调用 finish 方法时它不停止?

How to stop AsyncTask ? why it does not stop when calling finish method?

在我的应用程序中,我在通知抽屉上有一个进度条,当用户单击通知时,我会为此调用完成方法 activity,但进度条仍在工作。进度条在另一个class中的AsyncTask。我需要的是,我想停止上传进度条,并且当​​用户点击notification.Any帮助时Activity? 而我的代码是。

进度条

public void showProgressBar(){
    mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    mBuilder = new NotificationCompat.Builder(ImageUploadActivity.this);
    mBuilder.setContentTitle("Upload")
            .setContentText("Upload in progress")
            .setSmallIcon(R.drawable.ic_launcher);
    Intent myIntent = new Intent(this, ImageUploadActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(ImageUploadActivity.this, 0,   myIntent, Intent.FILL_IN_ACTION);
    // mBuilder.setAutoCancel(true);
    mBuilder.setContentIntent(pendingIntent);
   // myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
    mTask = new ImageUploadTask().execute();
   // new ImageUploadTask().execute();
}

异步任务

 class ImageUploadTask extends AsyncTask<Void,Integer, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        // Displays the progress bar for the first time.
        mBuilder.setProgress(100, 0, false);
        mNotifyManager.notify(id, mBuilder.build());



    }
    @Override
    protected void onProgressUpdate(Integer... values) {
        // Update progress
        mBuilder.setProgress(100, values[0], false);
        mNotifyManager.notify(id, mBuilder.build());
        super.onProgressUpdate(values);
    }
    @Override
    protected String doInBackground(Void... unsued) {
        int i;
        for (i = 0; i <= 100; i += 5) {
            // Sets the progress indicator completion percentage
            publishProgress(Math.min(i, 100));
            try {

                Thread.sleep(2 * 1000);
                HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();
                HttpPost httpPost = new HttpPost("http://10.1.1.1/test/upload.php");

                MultipartEntity entity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);

                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                byte[] data = bos.toByteArray();


          /* entity.addPart("uploaded_file", new ByteArrayBody(data,
                    "myImage.jpg"));*/

                // String newFilename= filename.concat("file");
                // newFilename=filename+newFilename;

                entity.addPart("uploaded_file", new ByteArrayBody(data,
                        filename));
                //  Log.e(TAG, "Method invoked");
                httpPost.setEntity(entity);
                HttpResponse response = httpClient.execute(httpPost,
                        localContext);
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(
                                response.getEntity().getContent(), "UTF-8"));

                StringBuilder builder = new StringBuilder();
                String aux = "";

                while ((aux = reader.readLine()) != null) {
                    builder.append(aux);
                }

                String sResponse = builder.toString();


                return sResponse;
            } catch (Exception e) {
             /*   if (dialog.isShowing())
                    dialog.dismiss();
                Toast.makeText(getApplicationContext(), "Exception Message 1", Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
                return null;*/
            }
        }
        return null;
    }


    @Override
    protected void onPostExecute(String result) {


        super.onPostExecute(result);
        mBuilder.setContentText("Upload completed");
        // Removes the progress bar
        mBuilder.setProgress(0, 0, false);
        mNotifyManager.notify(id, mBuilder.build());


    }
 }}

这里我调用finish方法

Button btnClosePopup = (Button) layout.findViewById(R.id.btn_cancel);

       btnClosePopup.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                mTask.cancel(true);
                ImageUploadActivity.this.finish();
                Toast.makeText(getApplicationContext(),
                        "Upload Cancelled", Toast.LENGTH_SHORT).show();

            }
        });

可以随时通过调用 cancel(boolean) 取消任务。调用此方法将导致对 isCancelled() 的后续调用变为 return true。调用此方法后,将在 doInBackground(Object[]) return 秒后调用 onCancelled(Object),而不是 onPostExecute(Object)

为确保尽快取消任务,如果可能(例如在循环内),您应该始终从 doInBackground(Object[]) 开始定期检查 isCancelled() 的 return 值.)

将下面的代码放在 doInBackground(Object[]) 方法的循环中。

if (isCancelled()) break;

详情请见下文link...

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

编辑:

 while ((aux = reader.readLine()) != null) {
    builder.append(aux);
    if (isCancelled()) break;
 }

您可以尝试如下..

  @Override
    protected String doInBackground(Void... unsued) {
        int i;
        for (i = 0; i <= 100; i += 5) {
            // Sets the progress indicator completion percentage

            //add this
            if (isCancelled())
              return null; 

            publishProgress(Math.min(i, 100));

并像这样重写 onCancelled

  @Override
 protected void onCancelled () 
{
ImageUploadActivity.this.finish();
                Toast.makeText(getApplicationContext(),
                        "Upload Cancelled", Toast.LENGTH_SHORT).show();
}