Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีใช้งาน AlarmManager ใน Android

การใช้งาน AlarmManager สำหรับตั้งเวลาปลุก/แจ้งเตือนใน Android

ตัวอย่างนี้สาธิตวิธีใช้ AlarmManager ร่วมกับ PendingIntent และ BroadcastReceiver เพื่อตั้งเวลาแจ้งเตือนเล่นเสียงนาฬิกาปลุก

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio เลือก File → New Project และกรอกข้อมูลที่จำเป็น

ขั้นตอนที่ 2: จัดทำ Layout (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="เริ่มต้น"
        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="วินาที"
        android:inputType="number" />
</RelativeLayout>

ขั้นตอนที่ 3: เขียนโค้ดหลัก (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 startButton;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        startButton = findViewById(R.id.button);
        startButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startAlert();
            }
        });
    }
    
    public void startAlert() {
        EditText timeEditText = findViewById(R.id.time);
        String timeText = timeEditText.getText().toString().trim();
        
        if (timeText.isEmpty()) {
            Toast.makeText(this, "กรุณากรอกจำนวนวินาที", Toast.LENGTH_SHORT).show();
            return;
        }
        
        int seconds = Integer.parseInt(timeText);
        
        Intent intent = new Intent(this, MyBroadcastReceiver.class);
        
        // ใช้ FLAG_IMMUTABLE สำหรับ Android 12+ (API 31+)
        int flags = PendingIntent.FLAG_UPDATE_CURRENT;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            flags |= PendingIntent.FLAG_IMMUTABLE;
        }
        
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
            this.getApplicationContext(), 
            234324243, 
            intent, 
            flags
        );
        
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        
        // ตั้งเวลา: RTC_WAKEUP = เปิดเครื่องจากสถานะสลีป
        long triggerTime = System.currentTimeMillis() + (seconds * 1000L);
        alarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
        
        Toast.makeText(this, "ตั้งนาฬิกาปลุกใน " + seconds + " วินาที", Toast.LENGTH_LONG).show();
    }
}

ขั้นตอนที่ 4: สร้าง 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) {
        try {
            // เล่นเสียงจาก res/raw/alarm.mp3
            mp = MediaPlayer.create(context, R.raw.alarm);
            if (mp != null) {
                mp.start();
            }
            Toast.makeText(context, "นาฬิกาปลุกดัง!", Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

ขั้นตอนที่ 5: เตรียมไฟล์เสียงนาฬิกาปลุก

  1. คลิกขวาที่ res → New → Android Resource Directory
  2. Resource type: raw
  3. วางไฟล์เสียง alarm.mp3 (หรือ .ogg) ใน res/raw/

ขั้นตอนที่ 6: กำหนดค่าใน 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>
        
        <!-- ลงทะเบียน BroadcastReceiver -->
        <receiver android:name=".MyBroadcastReceiver" 
                android:exported="false">
        </receiver>
    </application>
</manifest>

การทดสอบ

รันแอปพลิเคชัน กรอกจำนวนวินาที (เช่น 10) กดปุ่ม "เริ่มต้น" รอตามเวลา จะได้ยินเสียงนาฬิกาปลุก

วิธีใช้งาน AlarmManager ใน Android

วิธีใช้งาน AlarmManager ใน Android

ประเภท AlarmManager

ประเภท คำอธิบาย ปลุกเครื่องได้ไหม
RTC_WAKEUP เวลาจริง (wall clock) - ปลุกเครื่องจากสลีป ✅ ใช่
RTC เวลาจริง - ไม่ปลุกเครื่อง ❌ ไม่
ELAPSED_REALTIME_WAKEUP เวลาตั้งแต่บูท - ปลุกเครื่อง ✅ ใช่
ELAPSED_REALTIME เวลาตั้งแต่บูท - ไม่ปลุกเครื่อง ❌ ไม่

เมธอดตั้งค่า Alarm (API 19+ / KitKat)

  • set() - ประมาณเวลา (inexact) ประหยัดแบตเตอรี่
  • setExact() - เวลาถูกต้อง (exact) API 19-22
  • setExactAndAllowWhileIdle() - เวลาถูกต้อง แม้ Doze mode (API 23+)
  • setWindow() - ช่วงเวลา (window) API 19+
  • setRepeating() - ซ้ำ (deprecated สำหรับ exact repeating)

⚠️ ข้อจำกัด Android 6.0+ (Doze Mode)

  • Alarm แบบ inexact (set) อาจล่าช้าหลายนาที-ชั่วโมง
  • ใช้ setExactAndAllowWhileIdle() สำหรับ Alarm ที่ต้องแม่นยำ
  • ต้องขอ Permission REQUEST_IGNORE_BATTERY_OPTIMIZATIONS สำหรับแอปนาฬิกาปลุกจริง
  • WorkManager แนะนำสำหรับ Background work ที่ไม่ต้องแม่นยำ

WorkManager ทางเลือกใหม่ (แนะนำ)

// สำหรับงานที่ไม่ต้องแม่นยำเวลา
OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MyWorker.class)
    .setInitialDelay(10, TimeUnit.SECONDS)
    .build();
WorkManager.getInstance(context).enqueue(workRequest);