【问题标题】:How to stop AsyncTask ? why it does not stop when calling finish method?如何停止 AsyncTask ?为什么调用完成方法时它不会停止?
【发布时间】:2015-09-11 13:40:02
【问题描述】:

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


    }
 }}

这里我调用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();

            }
        });

【问题讨论】:

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

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


【解决方案1】:

你可以尝试如下..

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

【讨论】:

    【解决方案2】:

    可以通过调用cancel(boolean) 随时取消任务。调用此方法将导致对isCancelled() 的后续调用返回true。调用此方法后,onCancelled(Object) 将在 doInBackground(Object[]) 返回后调用,而不是 onPostExecute(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;
     }
    

    【讨论】:

    • 我在按钮单击时尝试了 mTask.cancel(true);(object of AsyncTask),并且 isCancelled () ) 中断; ,但问题仍然存在。怎么办?
    • 你把if (isCancelled()) break;放在while循环里面了吗?
    • 尝试在doInBackground(Object[])方法中也将其放入while循环中。
    • 如果doInBackground中没有while循环怎么办?
    • @MesterHassan 在这种情况下,需要检查您的代码 sn-p。请提出一个新问题并评论它的链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多