0

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

      } 
     }); 
+0

任务没有完成上停止(),因为它是异步的。所以当完成被调用时,所有其他同步进程将在活动的上下文中停止,但所有异步任务将继续运行。 – Neil

回答

2

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

为了确保任务是尽可能快地取消了,你应该总是定期从doInBackground(Object[])检查isCancelled()的返回值,如果可能的话(例如在一个循环中。)

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; 
} 
+0

我试过mTask.cancel(true);(AsyncTask的对象)按钮单击,isCancelled())break; ,但仍然存在问题。该怎么办? – Gibs

+0

你有把'if(isCancelled())break;'while while while循环吗? –

+0

是的,我把它放在代码中的for循环中 – Gibs

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