如何停止AsyncTask?调用完成方法时为什么不停止?

时间:2015-06-25 05:40:25

标签: android android-activity android-asynctask android-notifications android-progressbar

在我的应用程序中,我有一个进度条在通知抽屉上,当用户点击通知时,我调用该活动的完成方法,但进度条仍在工作。进度条在另一个类的AsyncTask中初始化。我需要的是,我想停止上传进度条,以及用户点击通知时的活动。任何帮助? 我的代码是。

进度

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

的AsyncTask

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


    }
 }}

我在这里调用结束方法

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

            }
        });

2 个答案:

答案 0 :(得分:2)

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

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

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

if (isCancelled()) break;

请参阅以下链接了解更多详情......

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

修改

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

答案 1 :(得分:0)

你可以尝试如下..

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