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

Cách tạo thông báo Android với BroadcastReceiver (đặt lịch)

Giới thiệu

Kết hợp AlarmManager + BroadcastReceiver để hiển thị thông báo tại thời điểm xác định trong tương lai, ngay cả khi app không chạy.

Kiến trúc

  1. MainActivity: UI chọn độ trễ (5s, 10s, 30s) qua Menu.
  2. MyNotificationPublisher (BroadcastReceiver): Nhận intent từ Alarm, gọi NotificationManager.notify().
  3. AlarmManager: Đặt hẹn giờ chính xác (ELAPSED_REALTIME_WAKEUP).

Code hoàn chỉnh

1. activity_main.xml (chỉ cần layout cơ bản)

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Mở menu (3 chấm) để chọn thời gian thông báo"
        android:textSize="16sp" />

</RelativeLayout>

2. res/menu/main_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto">
    <item android:id="@+id/action_5" android:title="5 giây" app:showAsAction="never" />
    <item android:id="@+id/action_10" android:title="10 giây" app:showAsAction="never" />
    <item android:id="@+id/action_30" android:title="30 giây" app:showAsAction="never" />
</menu>

3. MainActivity.java

package com.example.schedulednotification;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    public static final String CHANNEL_ID = "scheduled_channel";
    private static final String DEFAULT_CHANNEL = "default";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        createNotificationChannel();
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID, "Scheduled Notifications", NotificationManager.IMPORTANCE_HIGH);
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int delay = 0;
        String title = "";
        if (item.getItemId() == R.id.action_5) { delay = 5000; title = "5 giây"; }
        else if (item.getItemId() == R.id.action_10) { delay = 10000; title = "10 giây"; }
        else if (item.getItemId() == R.id.action_30) { delay = 30000; title = "30 giây"; }
        else return super.onOptionsItemSelected(item);

        scheduleNotification(title, delay);
        return true;
    }

    private void scheduleNotification(String content, int delayMillis) {
        Notification notification = buildNotification(content);

        Intent publisherIntent = new Intent(this, MyNotificationPublisher.class);
        publisherIntent.putExtra(MyNotificationPublisher.EXTRA_NOTIFICATION_ID, 1);
        publisherIntent.putExtra(MyNotificationPublisher.EXTRA_NOTIFICATION, notification);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this, 0, publisherIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);

        long triggerAtMillis = SystemClock.elapsedRealtime() + delayMillis;
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
    }

    private Notification buildNotification(String content) {
        return new NotificationCompat.Builder(this, DEFAULT_CHANNEL)
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentTitle("Thông báo hẹn giờ")
                .setContentText(content)
                .setAutoCancel(true)
                .setChannelId(CHANNEL_ID)
                .build();
    }
}

4. MyNotificationPublisher.java (BroadcastReceiver)

package com.example.schedulednotification;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

public class MyNotificationPublisher extends BroadcastReceiver {

    public static final String EXTRA_NOTIFICATION_ID = "notification-id";
    public static final String EXTRA_NOTIFICATION = "notification";

    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = intent.getParcelableExtra(EXTRA_NOTIFICATION);
        int id = intent.getIntExtra(EXTRA_NOTIFICATION_ID, 0);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    MainActivity.CHANNEL_ID, "Scheduled", NotificationManager.IMPORTANCE_HIGH);
            manager.createNotificationChannel(channel);
        }

        manager.notify(id, notification);
    }
}

5. AndroidManifest.xml

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

    <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" /> <!-- API 31+ -->
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <!-- API 33+ -->
    <uses-permission android:name="android.permission.VIBRATE" />

    <application ...>
        <activity android:name=".MainActivity" android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name=".MyNotificationPublisher"
            android:exported="false" />
    </application>
</manifest>

Lưu ý quan trọng về AlarmManager

Phương thứcĐộ chính xácĐánh thức thiết bịAPI yêu cầu
set()Không chính xác (batching)Có19+
setExact()Chính xácCó19+
setExactAndAllowWhileIdle()Chính xác, cho phép DozeCó23+
setAlarmClock()Rất chính xác, hiển thị icon báo thứcCó21+
Android 12+ (API 31): Cần quyền SCHEDULE_EXACT_ALARM trong Manifest và kiểm tra AlarmManager.canScheduleExactAlarms() tại runtime.

So sánh với WorkManager

  • AlarmManager + BroadcastReceiver: Chính xác đến giây, phù hợp báo thức, nhắc lịch chính xác.
  • WorkManager: Không đảm bảo thời điểm chính xác (window 15p+), nhưng tiết kiệm pin, hoạt động tốt khi reboot, phù hợp sync dữ liệu.