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 App Launcher Android bằng Kotlin

Giới thiệu

Hướng dẫn này minh họa cách hiển thị số lượng thông báo (badge count) trên icon ứng dụng trong Launcher Android sử dụng NotificationCompat.Builder.setNumber() và Kotlin.

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

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

Tạo project: File → New Project.

Bước 2: Thiết kế 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:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Tutorials Point"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="32sp"
        android:textStyle="bold" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:onClick="createNotification"
        android:text="Create Notification" />

</RelativeLayout>

Bước 3: Xử lý logic (src/MainActivity.kt)

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat

class MainActivity : AppCompatActivity() {
    private var count = 0
    private val channelId = "10001"
    private val defaultChannelId = "default"

    override fun onResume() {
        super.onResume()
        count = 0 // Reset count khi app mở lại
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
    }

    fun createNotification(view: View) {
        count++

        val notificationIntent = Intent(applicationContext, MainActivity::class.java).apply {
            putExtra("fromNotification", true)
            flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
        }

        val pendingIntent = PendingIntent.getActivity(
            this, 0, notificationIntent, 
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )

        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        val builder = NotificationCompat.Builder(this, defaultChannelId).apply {
            setContentTitle("My Notification")
            setContentIntent(pendingIntent)
            setContentText("Notification Listener Service Example")
            setSmallIcon(R.drawable.ic_launcher_foreground)
            setAutoCancel(true)
            setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL)
            setNumber(count) // QUAN TRỌNG: Set badge count
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val importance = NotificationManager.IMPORTANCE_HIGH
            val notificationChannel = NotificationChannel(
                channelId, "NOTIFICATION_CHANNEL_NAME", importance
            )
            builder.setChannelId(channelId)
            notificationManager.createNotificationChannel(notificationChannel)
        }

        notificationManager.notify(System.currentTimeMillis().toInt(), builder.build())
    }
}

Bước 4: Cấu hình Manifest (androidManifest.xml)

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

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

    <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 "Create Notification" nhiều lần. Mỗi lần count tăng, badge trên icon app launcher sẽ cập nhật số lượng (nếu launcher hỗ trợ).

Lưu ý quan trọng về Badge

  • Không phải tất cả Launcher đều hỗ trợ badge. Pixel Launcher, Nova, OneUI, MIUI, OxygenOS hỗ trợ tốt. Một số launcher cần cài đặt bật tính năng này.
  • setNumber() chỉ hoạt động nếu Launcher đọc notification badge.
  • Android 8.0+ (API 26+) bắt buộc phải có NotificationChannel.
  • Badge icon type: BADGE_ICON_SMALL (icon nhỏ) hoặc BADGE_ICON_LARGE (large icon).

Cách hiện đại: Notification Badge API (Android 8.0+)

Hệ thống tự động hiển thị badge dựa trên notification active. Không cần setNumber(). Để tắt badge cho channel:

val channel = NotificationChannel(channelId, name, importance).apply {
    setShowBadge(false) // Tắt badge cho channel này
}
notificationManager.createNotificationChannel(channel)

ShortcutBadger (Thư viện third-party)

Để hỗ trợ nhiều launcher hơn, dùng thư viện ShortcutBadger (đã ngưng cập nhật) hoặc MeLeShortcutBadger:

// build.gradle
implementation "me.leolin:ShortcutBadger:1.1.22@aar"

// Sử dụng
ShortcutBadger.applyCount(context, count)
ShortcutBadger.removeCount(context)

Kết luận

Cách tốt nhất hiện nay: Tạo notification đúng chuẩn với Channel, để hệ thống/launcher tự quản lý badge. Chỉ dùng setNumber() khi cần kiểm soát chính xác số hiển thị.