이 글에서는 Android 앱에서 AsyncTask에 시간 초과(Timeout)를 설정하는 방법을 단계별로 살펴봅니다. 사용자가 입력한 시간만큼 작업을 지연시키고, 진행 상황을 ProgressDialog로 표시한 뒤 완료되면 결과를 알려주는 예제입니다.
1단계: 새 프로젝트 생성
Android Studio에서 새 프로젝트를 만듭니다. 메뉴에서 File ⇒ New Project로 이동한 후, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하세요.
2단계: 레이아웃 파일 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 숫자를 입력받는 EditText와 비동기 작업을 실행하는 Button으로 구성된 간단한 화면입니다.
<?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" android:padding="16dp" tools:context=".MainActivity"> <EditText android:layout_marginTop="50dp" android:id="@+id/enterTime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:background="@android:drawable/editbox_background" android:inputType="number"/> <Button android:id="@+id/btnRun" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Run Async task" android:layout_below="@+id/enterTime" android:layout_centerHorizontal="true" /> </RelativeLayout>
3단계: MainActivity 작성
src/MainActivity.java 파일에 다음 코드를 추가합니다. 핵심은 doInBackground() 내부에서 Thread.sleep()으로 지정된 시간만큼 대기하고, onPreExecute()에서 ProgressDialog를 띄우며, onPostExecute()에서 이를 닫아주는 흐름입니다.
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button button;
EditText editTextTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.btnRun);
editTextTime = findViewById(R.id.enterTime);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AsyncTaskRunner runner = new AsyncTaskRunner();
String sleepTime = editTextTime.getText().toString();
runner.execute(sleepTime);
}
});
}
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
ProgressDialog progressDialog;
@Override
protected String doInBackground(String... params) {
publishProgress("AsyncTask started...");
String resp;
try {
int time = Integer.parseInt(params[0]) * 1000;
Thread.sleep(time);
resp = "Slept for " + params[0] + " seconds";
}
catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
@Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "AsyncTask Terminated", Toast.LENGTH_SHORT).show();
}
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this, "ProgressDialog", "Wait for " + editTextTime.getText().toString() + " seconds");
}
@Override
protected void onProgressUpdate(String... text) {
Toast.makeText(MainActivity.this, "" + text[0], Toast.LENGTH_SHORT).show();
}
}
}코드 동작 원리
- onPreExecute(): 작업 시작 전에 UI 스레드에서 ProgressDialog를 표시합니다.
- doInBackground(): 백그라운드 스레드에서 실행되며, 입력받은 초 단위 값을 밀리초로 변환해 Thread.sleep()으로 대기합니다.
- onProgressUpdate(): publishProgress() 호출 시 UI에 진행 상황을 Toast로 알립니다.
- onPostExecute(): 작업이 끝나면 ProgressDialog를 닫고 완료 메시지를 표시합니다.
4단계: AndroidManifest.xml 확인
androidManifest.xml 파일에 아래 코드가 올바르게 등록되어 있는지 확인합니다.
<?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 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run(실행) 아이콘을 클릭하세요. 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 나타납니다.

EditText에 원하는 초 단위 시간을 입력하고 버튼을 누르면 ProgressDialog가 표시되고, 지정한 시간이 지난 후 작업이 종료되었다는 Toast 메시지를 확인할 수 있습니다.

참고: AsyncTask는 더 이상 권장되지 않습니다
AsyncTask는 API 30(Android 11)부터 공식적으로 deprecated(사용 중단 권고) 되었으며, 위 예제의 ProgressDialog 역시 마찬가지입니다. 새 프로젝트에서는 Kotlin Coroutines(코루틴), ExecutorService, 또는 백그라운드 작업용 WorkManager를 사용하는 것이 좋습니다. 다만 기존 레거시 코드 유지보수 시에는 본 예제처럼 doInBackground() 내에서 시간 제한 로직을 직접 처리하거나, get(timeout, TimeUnit) 메서드를 활용해 타임아웃을 적용할 수 있습니다.