ภาพรวม
การแสดง Notification หลายรายการพร้อมกัน ทำได้โดยใช้ Notification ID ที่ต่างกัน สำหรับแต่ละ Notification ระบบจะแสดงแยกกันใน Shade นอกจากนี้ยังสามารถเพิ่มเสียง รัศมีแสง การสั่น และ Custom Sound ได้
ตัวอย่าง: สร้าง Notification หลายรายการพร้อมเสียงและเอฟเฟกต์
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
Android Studio → New Project → Empty Activity (Package: app.tutorialspoint.com.notifyme)
ขั้นตอนที่ 2: Layout (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="Create notification"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
ขั้นตอนที่ 3: เพิ่มไฟล์เสียง
สร้างโฟลเดอร์ res/raw/ และวางไฟล์เสียง (เช่น quite_impressed.mp3) ไว้
res/
└── raw/
└── quite_impressed.mp3
ขั้นตอนที่ 4: 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.Build;
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 -> createNotification());
}
private void createNotification() {
notificationCounter++;
// Custom Sound จาก res/raw
Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
getPackageName() + "/raw/quite_impressed.mp3");
// สร้าง Notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, DEFAULT_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Notification #" + notificationCounter)
.setContentText("Hello! This is notification number " + notificationCounter)
.setSound(soundUri)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// สร้าง Channel พร้อมการตั้งค่าขั้นสูง (Android 8.0+)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
NotificationChannel channel = new NotificationChannel(
NOTIFICATION_CHANNEL_ID,
"Multiple Notifications",
NotificationManager.IMPORTANCE_HIGH
);
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(soundUri, audioAttributes);
manager.createNotificationChannel(channel);
builder.setChannelId(NOTIFICATION_CHANNEL_ID);
}
// ใช้ ID ที่ต่างกันทุกครั้ง → แสดงหลายรายการ
int notificationId = (int) System.currentTimeMillis();
manager.notify(notificationId, builder.build());
}
}
ขั้นตอนที่ 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>
หลักการสำคัญ: Notification ID
- ID เดียวกัน: Notification ใหม่จะทับซ้อน (Update) Notification เก่า
- ID ต่างกัน: แสดงเป็นรายการแยกกันใน Shade
- ใช้
System.currentTimeMillis()หรือ Counter เพื่อสร้าง ID ที่ไม่ซ้ำ
การตั้งค่า Channel ขั้นสูง (API 26+)
| คุณสมบัติ | เมธอด | คำอธิบาย | |---|---|---| | **Importance** | `setImportance()` | ควบคุมระดับการแจ้งเตือน (HIGH = มีเสียง/หัวข้อ, DEFAULT = แจ้งเตือนปกติ, LOW = ไม่มีเสียง, MIN = เฉพาะ Shade) | | **เสียง** | `setSound()` | เสียงแจ้งเตือน (Custom หรือ Default) | | **การสั่น** | `enableVibration()`, `setVibrationPattern()` | รูปแบบการสั่น (array ของ milliseconds) | | **ไฟ LED** | `enableLights()`, `setLightColor()` | สีไฟ Notification LED (ถ้าอุปกรณ์รองรับ) | | **แสดงบน Lockscreen** | `setLockscreenVisibility()` | VISIBILITY_PUBLIC, PRIVATE, SECRET |การจัดการ Notification หลายรายการในทางปฏิบัติ
1. อัปเดต Notification เดียว (Progress, Download)
// ใช้ ID เดียวกัน เรียก notify() ซ้ำด้วย Builder ที่อัปเดต progress builder.setProgress(100, currentProgress, false); manager.notify(DOWNLOAD_ID, builder.build());
2. ลบ Notification เฉพาะรายการ
manager.cancel(notificationId); // ลบตาม ID manager.cancelAll(); // ลบทั้งหมดของแอป
3. จำกัดจำนวน Notification (ป้องกัน Spam)
// ตรวจสอบจำนวนก่อนสร้างใหม่
if (activeNotifications.size() >= MAX_NOTIFICATIONS) {
// ลบตัวเก่าสุด หรืออัปเดตตัวเดิมแทน
}
การทดสอบ
- รันแอป กดปุ่ม "Create notification" หลายครั้งติดต่อกัน
- ดู Notification Shade จะเห็นรายการแยกกันหลายรายการ
- แต่ละรายการมีเสียง รัศมีแสง และการสั่น ตามที่ตั้งค่า
- กดแต่ละรายการเพื่อ dismiss (เพราะ setAutoCancel(true))
แนวทางปฏิบัติ: อย่าสร้าง Notification มากเกินไปในเวลาสั้น จะรบกวนผู้ใช้ ควรจัดกลุ่ม (Grouping) หรืออัปเดต Notification เดิมแทน