Hướng dẫn này minh họa cách thực hiện tác vụ nền (background task) lặp lại định kỳ bằng AsyncTask kết hợp Handler.
Bước 1: Tạo dự án mới
Mở Android Studio, chọn File → New Project.
Bước 2: Giao diện đơn giản (res/layout/activity_main.xml)
<?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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="AsyncTask Demo"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
Bước 3: Logic lặp lại (src/MainActivity.java)
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
runRepeatingTask();
}
private void runRepeatingTask() {
new RepeatingTask().execute();
}
private class RepeatingTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
// Thực hiện tác vụ nền ở đây
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Lặp lại sau 5 giây
handler.postDelayed(this, 5000);
Toast.makeText(getApplicationContext(), "AsyncTask chạy mỗi 5 giây", Toast.LENGTH_SHORT).show();
}
}, 3000); // Delay lần đầu 3 giây
}
}
}
⚠️ Lưu ý quan trọng
AsyncTask đã bị deprecated kể từ API 30 (Android 11). Nên sử dụng các giải pháp hiện đại hơn:
- WorkManager — cho tác vụ nền có lịch trình, đảm bảo thực thi
- Kotlin Coroutines + Flow — cho lập trình bất đồng bộ hiện đại
- Handler + Runnable — cho tác vụ nhẹ, lặp lại đơn giản trên main thread
- ScheduledExecutorService — cho tác vụ nền phức tạp
Bước 4: Manifest (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>
Chạy ứng dụng
Kết nối thiết bị, nhấn Run. Màn hình sẽ hiển thị Toast mỗi 5 giây.