码桶

发现社区成员的开源项目

NotificationHelper.kt2.5 KB
package com.dalao.forum

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat

object NotificationHelper {

    const val CHANNEL_POSTS = "channel_posts"
    const val CHANNEL_COMMENTS = "channel_comments"
    const val CHANNEL_MESSAGES = "channel_messages"

    fun createChannels(context: Context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
        val manager = context.getSystemService(NotificationManager::class.java) ?: return

        val channels = listOf(
            Triple(CHANNEL_POSTS, R.string.channel_posts_name, R.string.channel_posts_desc),
            Triple(CHANNEL_COMMENTS, R.string.channel_comments_name, R.string.channel_comments_desc),
            Triple(CHANNEL_MESSAGES, R.string.channel_messages_name, R.string.channel_messages_desc)
        )
        channels.forEach { (id, nameRes, descRes) ->
            val channel = NotificationChannel(
                id, context.getString(nameRes), NotificationManager.IMPORTANCE_DEFAULT
            ).apply { description = context.getString(descRes) }
            manager.createNotificationChannel(channel)
        }
    }

    fun notify(context: Context, channelId: String, notifId: Int, title: String, content: String) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
            context.checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) !=
            PackageManager.PERMISSION_GRANTED
        ) {
            return
        }

        val tapIntent = Intent(context, SplashActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
        }
        val pendingIntent = PendingIntent.getActivity(
            context, notifId, tapIntent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        val notification = NotificationCompat.Builder(context, channelId)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle(title)
            .setContentText(content)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .build()

        NotificationManagerCompat.from(context).notify(notifId, notification)
    }
}