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

Phát âm thanh Notification mặc định trên Android

Để phát âm thanh thông báo hệ thống (notification sound) trên Android, sử dụng RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) kết hợp MediaPlayer hoặc gán trực tiếp vào Notification.

Các cách phát âm thanh

Cách 1: Phát âm thanh độc lập (MediaPlayer)

Phù hợp khi muốn phát âm thanh ngay lập tức không cần hiển thị notification.

Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
MediaPlayer mp = MediaPlayer.create(context, alarmSound);
mp.start();

// Tùy chọn: lắng nghe khi phát xong để release
mp.setOnCompletionListener(MediaPlayer::release);

Cách 2: Gán vào Notification (Builder)

Âm thanh sẽ phát khi notification xuất hiện (trên Android 7-). Trên Android 8+, âm thanh do NotificationChannel quyết định.

Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
    .setSmallIcon(R.drawable.ic_notification)
    .setContentTitle("Tiêu đề")
    .setContentText("Nội dung")
    .setSound(defaultSound); // Chỉ có hiệu lực pre-Oreo

Cách 3: Hoàn chỉnh - Tạo Notification có âm thanh (src/MainActivity.java)

package app.tutorialspoint.com.notifyme;

import android.app.NotificationManager;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
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 {
    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 -> {
            // 1. Phát âm thanh ngay lập tức qua MediaPlayer
            Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            MediaPlayer mp = MediaPlayer.create(getApplicationContext(), alarmSound);
            mp.start();

            // 2. Tạo notification
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, DEFAULT_CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentTitle("Test")
                .setContentText("Hello! This is my first push notification")
                .setAutoCancel(true);

            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (manager != null) {
                manager.notify((int) System.currentTimeMillis(), builder.build());
            }
        });
    }
}

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 thông báo + phát âm thanh"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

AndroidManifest.xml

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

    <uses-permission android:name="android.permission.VIBRATE" />

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

Các loại âm thanh hệ thống (RingtoneManager.TYPE_*)

Hằng sốMô tả
TYPE_RINGTONENhạc chuông cuộc gọi đến
TYPE_NOTIFICATIONÂm thanh thông báo (mặc định)
TYPE_ALARMÂm thanh báo thức
TYPE_ALLTất cả các loại trên

Lưu ý quan trọng

  • Android 8+ (Oreo): builder.setSound() bị bỏ qua. Phải cấu hình channel.setSound() khi tạo NotificationChannel (xem bài "Tùy chỉnh âm thanh Notification cho Android Oreo").
  • MediaPlayer: Nhớ gọi release() khi không dùng nữa để tránh rò rỉ tài nguyên. Dùng setOnCompletionListener để tự động release.
  • Quyền: Không cần quyền đặc biệt để phát âm thanh hệ thống. Quyền VIBRATE chỉ cần cho rung.