Android 如何停止异步任务?为什么调用finish方法时它不停止?

Android 如何停止异步任务?为什么调用finish方法时它不停止?,android,android-activity,android-asynctask,android-notifications,android-progressbar,Android,Android Activity,Android Asynctask,Android Notifications,Android Progressbar,在我的应用程序中,通知抽屉上有一个进度条,当用户单击通知时,我调用该活动的finish方法,但进度条仍在工作。进度条在另一个类的AsyncTask中初始化。我需要的是,我要停止上载进度条,当用户点击通知时的活动。有什么帮助吗? 我的代码是 进度条 public void showProgressBar(){ mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

在我的应用程序中,通知抽屉上有一个进度条,当用户单击通知时,我调用该活动的finish方法,但进度条仍在工作。进度条在另一个类的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();
}
异步任务

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


    }
 }}

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

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

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

if (isCancelled()) break;
请参阅下面的链接了解更多详细信息

编辑:

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

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

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

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

if (isCancelled()) break;
请参阅下面的链接了解更多详细信息

编辑:

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

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

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

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

if (isCancelled()) break;
请参阅下面的链接了解更多详细信息

编辑:

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

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

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

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

if (isCancelled()) break;
请参阅下面的链接了解更多详细信息

编辑:

 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));
你可以试试下面的方法

  @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));
你可以试试下面的方法

  @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));
你可以试试下面的方法

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

任务不会在finish()时停止,因为它是异步的。因此,当调用finish时,所有其他同步进程将在活动上下文中停止,但所有异步任务将继续运行。任务不会在finish()时停止,因为它是异步的。因此,当调用finish时,所有其他同步进程将在活动上下文中停止,但所有异步任务将继续运行。任务不会在finish()时停止,因为它是异步的。因此,当调用finish时,所有其他同步进程将在活动上下文中停止,但所有异步任务将继续运行。任务不会在finish()时停止,因为它是异步的。因此,当调用finish时,所有其他同步进程将在活动上下文中停止,但所有异步任务将继续运行;(AsyncTask的对象)在单击按钮时,isCancelled()中断,但问题仍然存在。该怎么办?你们有并没有把
if(isCancelled())中断内部while循环?尝试将其放入
doInBackground(Object[])
方法中的while循环。如果doInBackground中没有while循环,该怎么办?@MesterHassan在这种情况下,需要检查您的代码段。请提出新问题并评论其链接。我尝试了mTask。取消(true);(AsyncTask的对象)在单击按钮时,isCancelled()中断,但问题仍然存在。该怎么办?你们有并没有把
if(isCancelled())中断内部while循环?尝试将其放入
doInBackground(Object[])
方法中的while循环。如果doInBackground中没有while循环,该怎么办?@MesterHassan在这种情况下,需要检查您的代码段。请提出新问题并评论其链接。我尝试了mTask。取消(true);(AsyncTask的对象)在单击按钮时,isCancelled()中断,但问题仍然存在。该怎么办?你们有并没有把
if(isCancelled())中断内部while循环?尝试将其放入
doInBackground(Object[])
方法中的while循环。如果doInBackground中没有while循环,该怎么办?@MesterHassan在这种情况下,需要检查您的代码段。请提出新问题并评论其链接。我尝试了mTask。取消(true);(AsyncTask的对象)在单击按钮时,isCancelled()中断,但问题依然存在,该怎么办?