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

Cách hiển thị số lượng thông báo (Notification Badge) trên icon ứng dụng Android

Giới thiệu

Ví dụ này minh họa cách hiển thị số lượng (badge count) trên icon ứng dụng (launcher icon) khi có thông báo mới, sử dụng NotificationCompat.Builder.setNumber() và Notification Channel (Android 8.0+).

Các bước thực hiện

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project.

Bước 2: Giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:onClick="createNotification"
        android:text="Tạo thông báo" />

</RelativeLayout>

Bước 3: Code logic (src/MainActivity.java)

package com.app.sample;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import android.annotation.SuppressLint;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    private static int count = 0;
    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    private static final String DEFAULT_CHANNEL_ID = "default";

    @Override
    protected void onResume() {
        super.onResume();
        count = 0; // Reset khi app mở lại
    }

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

    @SuppressLint("WrongConstant")
    public void createNotification(View view) {
        count++;

        Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.putExtra("fromNotification", true);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? PendingIntent.FLAG_IMMUTABLE : 0);

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, DEFAULT_CHANNEL_ID);
        mBuilder.setContentTitle("Thông báo của tôi");
        mBuilder.setContentIntent(pendingIntent);
        mBuilder.setContentText("Ví dụ Notification Badge Count");
        mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
        mBuilder.setAutoCancel(true);
        mBuilder.setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL);
        mBuilder.setNumber(count); // Số hiển thị trên badge

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel notificationChannel = new NotificationChannel(
                    NOTIFICATION_CHANNEL_ID, "Kênh thông báo", importance);
            mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
            if (mNotificationManager != null) {
                mNotificationManager.createNotificationChannel(notificationChannel);
            }
        }

        if (mNotificationManager != null) {
            mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
        }
    }
}

Bước 4: Manifest (Manifests/AndroidManifest.xml)

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

    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <!-- Android 13+ cần quyền POST_NOTIFICATIONS -->
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

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

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Nhấn nút "Tạo thông báo" nhiều lần. Kéo màn hình thông báo xuống để thấy badge count tăng dần trên icon app.

Cách hiển thị số lượng thông báo (Notification Badge) trên icon ứng dụng Android

Cách hiển thị số lượng thông báo (Notification Badge) trên icon ứng dụng Android

Giải thích quan trọng

  • setNumber(count): Đặt số hiển thị trên badge. Chỉ hoạt động trên một số launcher (Pixel, OnePlus, Samsung One UI, v.v.). Không phải tất cả launcher đều hỗ trợ.
  • Notification Channel (API 26+): Bắt buộc phải tạo channel cho từng loại thông báo.
  • POST_NOTIFICATIONS (API 33+): Android 13 yêu cầu xin quyền runtime để hiển thị thông báo.
  • ShortcutBadger / Badge library: Để hỗ trợ rộng rãi hơn các launcher (Nova, Apex, v.v.), dùng thư viện me.leolin:ShortcutBadger (đã ngưng cập nhật) hoặc các thư viện mới hơn.

Cách hiện đại: Notification Badge với ShortcutManager (API 25+)

Android 7.1+ hỗ trợ badge trên app shortcut:

ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
if (shortcutManager != null && shortcutManager.isRequestPinShortcutSupported()) {
    ShortcutInfo shortcut = new ShortcutInfo.Builder(this, "notification_count")
            .setShortLabel("Thông báo")
            .setLongLabel("Bạn có " + count + " thông báo mới")
            .setIcon(Icon.createWithResource(this, R.drawable.ic_launcher_foreground))
            .build();
    shortcutManager.setDynamicShortcuts(Arrays.asList(shortcut));
}

Cách này hiển thị badge trên icon app trong launcher hỗ trợ (Pixel Launcher, Nova, v.v.).