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

Triển khai AlarmManager trong Android bằng Kotlin

Giới thiệu

Ví dụ này minh họa cách sử dụng AlarmManager để đặt báo thức lặp lại hàng ngày tại một giờ cụ thể do người dùng chọn qua TimePicker.

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, điền thông tin.

Bước 2: 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"
    android:padding="2dp"
    tools:context=".MainActivity">

    <TimePicker
        android:id="@+id/timePicker"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true" />

    <Button
        android:id="@+id/buttonAlarm"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/timePicker"
        android:layout_centerInParent="true"
        android:layout_marginTop="10dp"
        android:text="Set Alarm" />

</RelativeLayout>

Bước 3: MainActivity.kt

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TimePicker
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.util.Calendar

class MainActivity : AppCompatActivity() {
    private lateinit var btnSetAlarm: Button
    private lateinit var timePicker: TimePicker

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"

        timePicker = findViewById(R.id.timePicker)
        btnSetAlarm = findViewById(R.id.buttonAlarm)

        btnSetAlarm.setOnClickListener {
            val calendar = Calendar.getInstance().apply {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    set(
                        get(Calendar.YEAR),
                        get(Calendar.MONTH),
                        get(Calendar.DAY_OF_MONTH),
                        timePicker.hour,
                        timePicker.minute,
                        0
                    )
                } else {
                    @Suppress("DEPRECATION")
                    set(
                        get(Calendar.YEAR),
                        get(Calendar.MONTH),
                        get(Calendar.DAY_OF_MONTH),
                        timePicker.currentHour,
                        timePicker.currentMinute,
                        0
                    )
                }
            }
            setAlarm(calendar.timeInMillis)
        }
    }

    private fun setAlarm(timeInMillis: Long) {
        val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val intent = Intent(this, MyAlarm::class.java)
        val pendingIntent = PendingIntent.getBroadcast(
            this, 0, intent,
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )

        alarmManager.setRepeating(
            AlarmManager.RTC_WAKEUP,
            timeInMillis,
            AlarmManager.INTERVAL_DAY,
            pendingIntent
        )
        Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show()
    }
}

class MyAlarm : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        Log.d("Alarm Bell", "Alarm just fired")
        // Tại đây có thể hiển thị Notification, phát âm thanh, v.v.
    }
}

Lưu ý: Sử dụng PendingIntent.FLAG_IMMUTABLE (bắt buộc từ Android 12) và AlarmManager.RTC_WAKEUP để đánh thức thiết bị.

Bước 4: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.q11">

    <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>

        <receiver android:name=".MainActivity$MyAlarm" android:exported="false" />

    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Chọn giờ trên TimePicker, nhấn "Set Alarm". Báo thức sẽ kích hoạt mỗi ngày tại giờ đó.

Lưu ý: Từ Android 12 (API 31), cần quyền SCHEDULE_EXACT_ALARM cho báo thức chính xác. Cân nhắc dùng WorkManager cho các tác vụ nền tin cậy hơn.