Giới thiệu
Hướng dẫn này trình bày cách sử dụng AlarmManager để lên lịch thực hiện công việc tại một thời điểm trong tương lai (ví dụ: báo thức, nhắc nhở).
Các bước thực hiện
Bước 1: Tạo dự án mới
Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.
Bước 2: Thiết kế giao diệ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">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bắt đầu"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="103dp" />
<EditText
android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:ems="10"
android:hint="Giây"
android:inputType="number" />
</RelativeLayout>
Bước 3: Logic chính (src/MainActivity.java)
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
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 start;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = findViewById(R.id.button);
start.setOnClickListener(v -> startAlert());
}
public void startAlert() {
EditText text = findViewById(R.id.time);
int seconds = Integer.parseInt(text.getText().toString());
// Intent đến BroadcastReceiver
Intent intent = new Intent(this, MyBroadcastReceiver.class);
// PendingIntent cho Broadcast
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(),
234324243, // Request code (unique)
intent,
PendingIntent.FLAG_IMMUTABLE // API 23+ required
);
// Lấy AlarmManager
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
// Đặt alarm: RTC_WAKEUP = đánh thức thiết bị nếu đang ngủ
// Thời điểm: hiện tại + seconds * 1000ms
alarmManager.set(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + (seconds * 1000),
pendingIntent);
Toast.makeText(this, "Đã đặt báo thức sau " + seconds + " giây", Toast.LENGTH_LONG).show();
}
}
Bước 4: Tạo BroadcastReceiver (MyBroadcastReceiver.java)
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver {
MediaPlayer mp;
@Override
public void onReceive(Context context, Intent intent) {
// Phát âm thanh báo thức (file alarm.mp3 trong res/raw/)
mp = MediaPlayer.create(context, R.raw.alarm);
mp.start();
Toast.makeText(context, "BÁO THỨC!!! ⏰", Toast.LENGTH_LONG).show();
}
}
Bước 5: Cấu hình 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>
<!-- Đăng ký BroadcastReceiver -->
<receiver android:name=".MyBroadcastReceiver"
android:exported="false">
</receiver>
</application>
</manifest>
Bước 6: Thêm file âm thanh
- Chuột phải
res→ New → Android Resource Directory - Resource type:
raw→ OK - Copy file âm thanh (alarm.mp3/ogg) vào
res/raw/alarm.mp3
Các loại AlarmManager.set()
| Phương thức | Mô tả |
|---|---|
set() |
Chạy một lần, thời điểm gần đúng (hệ thống tối ưu pin) |
setExact() |
Chạy một lần, thời điểm chính xác (API 19+) |
setExactAndAllowWhileIdle() |
Chạy chính xác ngay cả khi Doze mode (API 23+) |
setRepeating() |
Lặp lại (không chính xác từ API 19+) |
setInexactRepeating() |
Lặp lại không chính xác (tiết kiệm pin) |
Lưu ý quan trọng
- Từ Android 6.0 (Doze mode), alarm không chính xác nếu không dùng
setExactAndAllowWhileIdle() - Cần quyền
android.permission.SCHEDULE_EXACT_ALARM(API 31+) cho alarm chính xác - PendingIntent cần flag
FLAG_IMMUTABLEhoặcFLAG_MUTABLE(API 23+) - AlarmManager không bền vững qua reboot - cần BootReceiver để đăng ký lại
Chạy ứng dụng
Kết nối thiết bị Android, nhấn Run trong Android Studio. Nhập số giây, nhấn "Bắt đầu", đợi đến giờ sẽ nghe âm thanh báo thức.

