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

Hiển thị nhiều Notification cùng lúc trên Android

Để hiển thị nhiều notification độc lập cùng một lúc, chỉ cần gọi NotificationManager.notify() với ID khác nhau cho mỗi notification. Android sẽ hiển thị tất cả trong thanh trạng thái.

Các bước thực hiện

Bước 1: Tạo dự án mới

Tạo dự án Android Studio, package app.tutorialspoint.com.notifyme.

Bước 2: Chuẩn bị âm thanh (res/raw/)

Đặt file âm thanh (ví dụ: quite_impressed.mp3) vào thư mục res/raw/. Tạo thư mục nếu chưa có: New → Android Resource Directory → Resource type: raw.

Bước 3: Giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnCreateNotification"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Tạo nhiều thông báo"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Bước 4: Tạo nhiều notification với ID khác nhau (src/MainActivity.java)

package app.tutorialspoint.com.notifyme;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Color;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Bundle;
import androidx.core.app.NotificationCompat;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    private static final String DEFAULT_CHANNEL_ID = "default";
    private int notificationCounter = 0;

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

        Button btnCreateNotification = findViewById(R.id.btnCreateNotification);
        btnCreateNotification.setOnClickListener(v -> createMultipleNotifications());
    }

    private void createMultipleNotifications() {
        // Tạo 3 notification cùng lúc với ID khác nhau
        for (int i = 1; i <= 3; i++) {
            notificationCounter++;
            int notificationId = notificationCounter; // ID duy nhất

            Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" 
                + getPackageName() + "/raw/quite_impressed.mp3");

            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, DEFAULT_CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentTitle("Thông báo #" + i)
                .setContentText("Đây là thông báo thứ " + i + " được tạo cùng lúc")
                .setSound(sound)
                .setAutoCancel(true);

            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_ALARM)
                    .build();

                int importance = NotificationManager.IMPORTANCE_HIGH;
                NotificationChannel channel = new NotificationChannel(
                    NOTIFICATION_CHANNEL_ID, "Kênh đa thông báo", importance);
                channel.enableLights(true);
                channel.setLightColor(Color.RED);
                channel.enableVibration(true);
                channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
                channel.setSound(sound, audioAttributes);
                manager.createNotificationChannel(channel);
                builder.setChannelId(NOTIFICATION_CHANNEL_ID);
            }

            manager.notify(notificationId, builder.build());
        }
    }
}

Bước 5: AndroidManifest.xml

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

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

Nguyên tắc quan trọng

  • ID duy nhất: Mỗi notification cần ID int khác nhau trong manager.notify(id, notification). Nếu trùng ID, notification mới sẽ ghi đè notification cũ.
  • Notification Channel: Từ Android 8.0, tất cả notification phải thuộc một channel. Các notification cùng channel sẽ có hành vi giống nhau (âm thanh, rung, độ ưu tiên).
  • Giới hạn: Android giới hạn số notification hiển thị (thường 50-100). Notification cũ sẽ bị ẩn khi quá nhiều.

Quản lý notification

// Xóa một notification cụ thể
manager.cancel(notificationId);

// Xóa tất cả notification của app
manager.cancelAll();