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

เสียง Notification แบบกำหนดเองสำหรับ Android Oreo (API 26) ขึ้นไป

ภาพรวม

ตั้งแต่ Android 8.0 (Oreo, API 26) การตั้งค่าเสียง Notification เปลี่ยนไป ต้องผ่าน Notification Channel เท่านั้น ไม่สามารถตั้งค่าเสียงผ่าน NotificationCompat.Builder.setSound() โดยตรงได้อีกต่อไป ต้องตั้งค่าที่ Channel Level

ตัวอย่าง: ใช้ไฟล์เสียง Custom จาก res/raw

ขั้นตอนที่ 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 (หรือ .ogg, .wav)

ขั้นตอนที่ 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";

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

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

    private void createNotificationWithCustomSound() {
        // URI ของไฟล์เสียงใน res/raw
        Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + 
                getPackageName() + "/raw/quite_impressed.mp3");

        // Builder พื้นฐาน (ไม่ต้อง setSound ที่นี่สำหรับ Android 8.0+)
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, DEFAULT_CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentTitle("Custom Sound Notification")
                .setContentText("Hello! This uses custom sound from raw folder")
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setAutoCancel(true);

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

        // สร้าง Channel พร้อมเสียง Custom (Android 8.0+)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // AudioAttributes - ระบุประเภทและวัตถุประสงค์ของเสียง
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .build();

            NotificationChannel channel = new NotificationChannel(
                    NOTIFICATION_CHANNEL_ID,
                    "Custom Sound Notifications",
                    NotificationManager.IMPORTANCE_HIGH
            );
            channel.setDescription("Notifications with custom sound from raw resource");
            channel.enableLights(true);
            channel.setLightColor(Color.BLUE);
            channel.enableVibration(true);
            channel.setVibrationPattern(new long[]{0, 200, 100, 200});
            
            // สำคัญ: ตั้งค่าเสียงที่ Channel Level
            channel.setSound(soundUri, audioAttributes);
            
            manager.createNotificationChannel(channel);
            builder.setChannelId(NOTIFICATION_CHANNEL_ID);
        } else {
            // Android 7.1 และก่อน: ใช้ setSound โดยตรงได้
            builder.setSound(soundUri);
        }

        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>

การเปลี่ยนแปลงสำคัญใน Android 8.0+ (API 26+)

ก่อน API 26API 26+
builder.setSound(uri)channel.setSound(uri, audioAttributes)
builder.setVibrate(pattern)channel.setVibrationPattern(pattern)
builder.setLights(color, onMs, offMs)channel.enableLights(true), channel.setLightColor(color)
builder.setPriority()channel.setImportance()

AudioAttributes - สำคัญสำหรับเสียง

AudioAttributes audioAttributes = new AudioAttributes.Builder()
    .setUsage(AudioAttributes.USAGE_NOTIFICATION)      // ประเภทการใช้งาน
    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) // ประเภทเนื้อหา
    .build();

Usage Types

  • USAGE_NOTIFICATION: การแจ้งเตือนทั่วไป (ค่าเริ่มต้น)
  • USAGE_ALARM: นาฬิกาปลุก (บังคับเล่นแม้โหมดเงียบ)
  • USAGE_NOTIFICATION_RINGTONE: เสียงโทรเข้า
  • USAGE_NOTIFICATION_COMMUNICATION_REQUEST: โทร/วิดีโอคอล
  • USAGE_NOTIFICATION_COMMUNICATION_INSTANT: ข้อความทันที

Content Types

  • CONTENT_TYPE_SONIFICATION: เสียงระบบ/การแจ้งเตือน (ค่าเริ่มต้น)
  • CONTENT_TYPE_SPEECH: เนื้อหาพูด
  • CONTENT_TYPE_MUSIC: เพลง

ข้อควรระวัง

  1. Channel สร้างครั้งเดียว: เรียก createNotificationChannel() ซ้ำไม่มีผล (ยกเว้นการอัปเดตบางอย่าง)
  2. ผู้ใช้ควบคุมได้: User สามารถปิดเสียง/การสั่นของ Channel ได้ใน Settings
  3. ไฟล์เสียง: ใช้ .ogg หรือ .mp3 ขนาดเล็ก (< 1MB) วางใน res/raw/
  4. Default Sound: ใช้ RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) แทน custom sound

การทดสอบ

  1. รันแอปบนอุปกรณ์ API 26+
  2. กดปุ่มสร้าง Notification
  3. ตรวจสอบว่าเล่นเสียง custom ที่กำหนด
  4. ไป Settings → Apps → Notifications → Channel → ตรวจสอบการตั้งค่าเสียง
เคล็ดลับ: หากต้องการเปลี่ยนเสียงหลังสร้าง Channel แล้ว ต้องสร้าง Channel ใหม่ด้วย ID ใหม่ (Channel ไม่รองรับการอัปเดตเสียงหลังสร้าง)