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

Tạo và quản lý Notification Channel trên Android (API 26+)

Từ Android 8.0 (API 26), Notification Channel là bắt buộc. Mỗi kênh định nghĩa hành vi chung cho nhóm notification: độ quan trọng, âm thanh, rung, đèn LED, có hiển thị heads-up hay không. Người dùng có thể tùy chỉnh từng kênh trong Cài đặt.

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/quite_impressed.mp3)

Đặt file âm thanh vào res/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 thông báo demo Channel"
        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 Channel đầy đủ tính năng (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 CHANNEL_ID_HIGH = "channel_high_priority";
    public static final String CHANNEL_ID_LOW = "channel_low_priority";
    private static final String DEFAULT_CHANNEL_ID = "default";

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

        // Tạo các channel khi app khởi động (nên làm trong Application class)
        createNotificationChannels();

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

    private void createNotificationChannels() {
        NotificationManager manager = getSystemService(NotificationManager.class);
        if (manager == null) return;

        // Chỉ tạo trên API 26+
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.O) return;

        // === Kênh 1: Ưu tiên cao (High importance) ===
        Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" 
            + getPackageName() + "/raw/quite_impressed.mp3");

        AudioAttributes audioAttributes = new AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
            .setUsage(AudioAttributes.USAGE_NOTIFICATION)
            .build();

        NotificationChannel highChannel = new NotificationChannel(
            CHANNEL_ID_HIGH, 
            "Thông báo quan trọng", 
            NotificationManager.IMPORTANCE_HIGH  // Heads-up, âm thanh, rung
        );
        highChannel.setDescription("Thông báo cần xử lý ngay: tin nhắn, cuộc gọi, cảnh báo");
        highChannel.enableLights(true);
        highChannel.setLightColor(Color.RED);
        highChannel.enableVibration(true);
        highChannel.setVibrationPattern(new long[]{0, 300, 200, 300});
        highChannel.setSound(soundUri, audioAttributes);
        highChannel.setShowBadge(true); // Hiển thị badge trên icon app

        // === Kênh 2: Ưu tiên thấp (Low importance) ===
        NotificationChannel lowChannel = new NotificationChannel(
            CHANNEL_ID_LOW,
            "Thông báo thường",
            NotificationManager.IMPORTANCE_LOW  // Không heads-up, không âm thanh, chỉ hiển thị trong shade
        );
        lowChannel.setDescription("Thông báo không gấp: khuyến mãi, cập nhật, nhắc nhở nhẹ");
        lowChannel.setShowBadge(false);

        // Đăng ký cả 2 kênh
        manager.createNotificationChannels(java.util.Arrays.asList(highChannel, lowChannel));
    }

    private void showNotificationWithHighChannel() {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID_HIGH)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle("Thông báo quan trọng")
            .setContentText("Đây dùng kênh HIGH - sẽ hiện heads-up, phát âm thanh, rung")
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setAutoCancel(true);

        NotificationManager manager = getSystemService(NotificationManager.class);
        if (manager != null) {
            manager.notify((int) System.currentTimeMillis(), 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>

Các mức độ quan trọng (Importance Levels)

Mức độHành vi mặc địnhPhù hợp cho
IMPORTANCE_HIGHHeads-up, âm thanh, rung, badgeTin nhắn, cuộc gọi, cảnh báo khẩn cấp
IMPORTANCE_DEFAULTÂm thanh, rung, không heads-upThông báo thông thường
IMPORTANCE_LOWKhông âm thanh, không rung, chỉ trong shadeCập nhật app, khuyến mãi
IMPORTANCE_MINChỉ hiển thị khi kéo shade xuốngThông tin nền, debug log
IMPORTANCE_NONEKhông hiển thị gì cảTracking, analytics

Quản lý Channel nâng cao

// Lấy kênh đã tạo
NotificationChannel channel = manager.getNotificationChannel(CHANNEL_ID_HIGH);

// Xóa kênh (notification trong kênh vẫn hiển thị cho đến khi bị xóa)
manager.deleteNotificationChannel(CHANNEL_ID_LOW);

// Lấy danh sách tất cả kênh
List<NotificationChannel> channels = manager.getNotificationChannels();

// Cho phép user điều chỉnh cài đặt kênh
Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS)
    .putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName())
    .putExtra(Settings.EXTRA_CHANNEL_ID, CHANNEL_ID_HIGH);
startActivity(intent);

Best practice: Tạo Channel trong class extends Application (method onCreate()) để đảm bảo sẵn sàng trước khi FCM hoặc Worker gửi notification.