이 예제는 안드로이드에서 실행 중인 AsyncTask 스레드를 중지(취소)하는 방법을 단계별로 보여줍니다. 핵심은 cancel(true) 메서드를 호출하고, doInBackground() 내부에서 isCancelled()를 주기적으로 확인하여 작업을 안전하게 종료하는 것입니다.
1단계 – 새 프로젝트 생성
Android Studio에서 File ⇒ New Project를 선택하여 새 프로젝트를 만들고, 필요한 모든 세부 정보를 입력합니다.
2단계 – 레이아웃 파일 작성 (res/layout/activity_main.xml)
버튼 두 개(작업 시작, 취소)와 진행 상태를 표시할 TextView를 추가한 레이아웃입니다.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/btnDo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@id/btnCancel" android:layout_centerInParent="true" android:layout_marginBottom="25sp" android:text="Do AsyncTask" /> <Button android:id="@+id/btnCancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@id/textView" android:layout_centerInParent="true" android:layout_marginBottom="20dp" android:text="Cancel" /> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textSize="20sp" android:gravity="center_horizontal" /> </RelativeLayout>
3단계 – 메인 액티비티 코드 작성 (src/MainActivity.java)
아래 코드가 이 예제의 핵심입니다. [Do AsyncTask] 버튼을 누르면 5개의 작업(Task1~Task5)이 순차적으로 실행되고, [Cancel] 버튼을 누르면 myTask.cancel(true)가 호출되어 백그라운드 스레드에 인터럽트가 발생합니다. 이후 doInBackground()의 반복문 안에서 isCancelled()가 true를 반환하면 루프를 빠져나오고, onPostExecute() 대신 onCancelled()가 호출됩니다.
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Button btnDo, btnCancel;
private TextView textView;
private AsyncTask myTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnDo = findViewById(R.id.btnDo);
btnCancel = findViewById(R.id.btnCancel);
textView = findViewById(R.id.textView);
btnDo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textView.setText("");
myTask = new DownloadTask().execute("Task1",
"Task2", "Task3", "Task4", "Task5");
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myTask.cancel(true);
}
});
}
private class DownloadTask extends AsyncTask<String, Integer, List<String>> {
@Override
protected void onPreExecute() {
super.onPreExecute();
textView.setTextColor(Color.BLUE);
textView.setText(textView.getText() + "\n Starting Task....");
}
@Override
protected List<String> doInBackground(String... tasks) {
int count = tasks.length;
List<String> taskList= new ArrayList<>(count);
for(int i =0;i<count;i++){
String currentTask = tasks[i];
taskList.add(currentTask);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress((int) (((i+1) / (float) count) * 100));
if(isCancelled()){
break;
}
}
return taskList;
}
@Override
protected void onCancelled() {
super.onCancelled();
textView.setTextColor(Color.RED);
textView.setText(textView.getText() + "\n Operation is cancelled..");
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
textView.setText(textView.getText()+ "\n Completed:)" + progress[0] + "%");
}
@Override
protected void onPostExecute(List<String> result) {
super.onPostExecute(result);
textView.setText(textView.getText() + "\n\n Done....");
for (int i=0;i<result.size();i++){
textView.setText(textView.getText() + "\n" +
result.get(i));
}
}
}
}취소 로직 동작 원리 정리
- cancel(true): 백그라운드 스레드에 인터럽트(interrupt)를 발생시켜 취소를 요청합니다.
- isCancelled():
doInBackground()내에서 주기적으로 호출하여 취소 요청 여부를 확인하고, true면 즉시 작업을 종료해야 합니다. - onCancelled(): 작업이 취소되면
onPostExecute()대신 이 콜백이 UI 스레드에서 호출됩니다. - Thread.sleep() 중 인터럽트 발생 시: InterruptedException이 던져지므로 catch 블록에서 적절히 처리하거나 루프를 종료하는 것이 좋습니다.
4단계 – 매니페스트 설정 (androidManifest.xml)
매니페스트 파일에 아래와 같이 MainActivity를 등록합니다.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run ▶ 아이콘을 클릭하고, 옵션 목록에서 자신의 모바일 기기를 선택하세요. 그러면 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

[Do AsyncTask] 버튼을 누르면 파란색 텍스트로 작업 시작과 함께 진행률(Completed: 20%, 40%...)이 표시됩니다. 진행 도중 [Cancel] 버튼을 누르면 빨간색으로 "Operation is cancelled.." 메시지가 출력되며 작업이 즉시 중단됩니다.

이처럼 cancel(true)와 isCancelled()를 조합하면 실행 중인 AsyncTask를 안전하게 중지할 수 있습니다. 다만 참고로, AsyncTask는 API 30부터 공식적으로 지원 중단(deprecated)되었으므로 최신 프로젝트에서는 Kotlin Coroutines나 WorkManager 사용을 권장합니다.