Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách hủy AsyncTask đang thực thi trong Android

Giới thiệu về AsyncTask

AsyncTask cho phép chạy tác vụ nền (background) và cập nhật UI. Để hủy: asyncTask.cancel(true) - tham số true nghĩa là interrupt thread nếu đang chạy.

⚠️ QUAN TRỌNG: AsyncTask đã DEPRECATED từ API 30 (Android 11). Google khuyến nghị dùng:
• Kotlin Coroutines (suspend functions, structured concurrency)
• ExecutorService / ThreadPoolExecutor
• WorkManager (deferred/guaranteed execution)
• RxJava / Flow / LiveData reactive streams

Ví dụ: Hủy download ảnh AsyncTask

Bước 1: Tạo dự án mới

Android Studio → File → New Project.

Bước 2: Giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/rootview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#C1C1C1"
    android:gravity="center_horizontal"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/asyncTask"
        android:text="Tải ảnh"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ImageView
        android:id="@+id/image"
        android:layout_width="300dp"
        android:layout_height="300dp" />

</LinearLayout>

Bước 3: MainActivity với AsyncTask có thể hủy (src/MainActivity.java)

package com.example.andy.myapplication;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    URL imageUrl = null;
    InputStream is = null;
    Bitmap bmImg = null;
    ImageView imageView = null;
    DownloadTask asyncTask = null;
    ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = findViewById(R.id.asyncTask);
        imageView = findViewById(R.id.image);

        button.setOnClickListener(v -> {
            asyncTask = new DownloadTask();
            asyncTask.execute("https://www.tutorialspoint.com/images/tp-logo-diamond.png");
        });
    }

    private class DownloadTask extends AsyncTask {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setMessage("Đang tải... (nhấn ngoài để hủy)");
            progressDialog.setIndeterminate(true);
            progressDialog.setCancelable(true);
            progressDialog.setOnCancelListener(dialog -> {
                asyncTask.cancel(true); // HỦY ASYNCTASK
                Toast.makeText(MainActivity.this, "AsyncTask đã dừng", Toast.LENGTH_LONG).show();
            });
            progressDialog.show();
        }

        @Override
        protected Bitmap doInBackground(String... urls) {
            try {
                Thread.sleep(10000); // Giả lập tải chậm 10s
                imageUrl = new URL(urls[0]);
                HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                is = conn.getInputStream();
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Bitmap.Config.RGB_565;
                bmImg = BitmapFactory.decodeStream(is, null, options);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return bmImg;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if (imageView != null && !isCancelled()) { // KIỂM TRA isCancelled()
                progressDialog.dismiss();
                imageView.setImageBitmap(bitmap);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) {
            asyncTask.cancel(true);
        }
    }
}

Các điểm then chốt để hủy thành công

  1. asyncTask.cancel(true): Gửi interrupt đến thread nền
  2. Trong doInBackground: Nên kiểm tra isCancelled() định kỳ để thoát sớm
  3. Thread.sleep() ném InterruptedException khi bị cancel(true)
  4. Trong onPostExecute: Kiểm tra !isCancelled() trước khi cập nhật UI
  5. ProgressDialog.setOnCancelListener: Hủy khi user dismiss dialog

Chạy ứng dụng

Chạy app → Nhấn "Tải ảnh" → ProgressDialog hiện. Nhấn ra ngoài dialog → Toast "AsyncTask đã dừng", download bị hủy. Nếu không hủy → Ảnh hiển thị sau 10s.