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

Thêm Rung và Âm thanh cho Notification Android

Để thêm cả rung (vibrate) và âm thanh (sound) cho Notification, trên Android 7- dùng Builder.setVibrate() và Builder.setSound(). Trên Android 8+ (Oreo), phải cấu hình trên NotificationChannel.

Code hoàn chỉnh (src/MainActivity.java)

package app.tutorialspoint.com.notifyme;

import android.app.NotificationManager;
import android.content.Context;
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 -> createNotificationWithVibrateAndSound());
    }

    private void createNotificationWithVibrateAndSound() {
        // Âm thanh mặc định hệ thống
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_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);

        // Cấu hình rung (pattern: delay, rung, delay, rung... đơn vị ms)
        // Chỉ có hiệu lực trên Android 7- hoặc nếu Channel không set vibration
        builder.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});

        // Cấu hình âm thanh (chỉ pre-Oreo)
        builder.setSound(alarmSound);

        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 có rung + â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 (cần quyền VIBRATE)

<?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ách đúng cho Android 8+ (Oreo): Cấu hình trên NotificationChannel

Code trên chỉ hoạt động đầy đủ trên Android 7-. Trên Android 8+, hãy tạo Channel có rung và âm thanh:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    AudioAttributes attrs = new AudioAttributes.Builder()
        .setUsage(AudioAttributes.USAGE_NOTIFICATION)
        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
        .build();

    NotificationChannel channel = new NotificationChannel(
        "channel_id", "Tên kênh", NotificationManager.IMPORTANCE_HIGH);
    channel.setSound(sound, attrs);
    channel.enableVibration(true);
    channel.setVibrationPattern(new long[]{0, 500, 200, 500}); // delay, rung, delay, rung...
    
    manager.createNotificationChannel(channel);
    builder.setChannelId("channel_id");
}

Giải thích Vibration Pattern

Mảng long[] định nghĩa: {delay, rung, delay, rung, ...} (đơn vị millisecond).

  • {1000, 1000, 1000, 1000, 1000}: Đợi 1s → Rung 1s → Đợi 1s → Rung 1s → Đợi 1s
  • {0, 500, 200, 500}: Rung ngay 500ms → Nghỉ 200ms → Rung 500ms
  • Phần tử đầu tiên luôn là delay ban đầu (thường là 0 để rung ngay).

Lưu ý

  • Quyền android.permission.VIBRATE bắt buộc trong Manifest.
  • Trên Android 8+, builder.setVibrate() và builder.setSound() bị bỏ qua nếu Channel đã tồn tại.
  • Để test thay đổi pattern/sound trên Oreo+: gỡ app và cài lại, hoặc user vào Cài đặt → Apps → Notifications → Channel để chỉnh.