57 lines
2.4 KiB
Kotlin
57 lines
2.4 KiB
Kotlin
package core.notifications.data
|
|
|
|
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 androidx.core.app.NotificationCompat
|
|
|
|
object NotificationHelper {
|
|
private const val CHANNEL_ID = "fork_notifications_channel"
|
|
|
|
fun showNotification(context: Context, title: String?, body: String?, type: String?, chatId: String? = null, notificationId: Int? = null, totalCount: Int = 0) {
|
|
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
|
|
|
val finalNotificationId = notificationId ?: (System.currentTimeMillis() % Int.MAX_VALUE).toInt()
|
|
|
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
|
val channel = NotificationChannel(
|
|
CHANNEL_ID,
|
|
"Fork Messenger Notifications",
|
|
NotificationManager.IMPORTANCE_HIGH
|
|
).apply {
|
|
description = "Chat and system notifications"
|
|
}
|
|
notificationManager.createNotificationChannel(channel)
|
|
}
|
|
|
|
// Find our launcher activity via package manager to avoid static dependency on MainActivity
|
|
val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)?.apply {
|
|
action = Intent.ACTION_MAIN
|
|
addCategory(Intent.CATEGORY_LAUNCHER)
|
|
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
|
putExtra("type", type)
|
|
putExtra("chatId", chatId)
|
|
} ?: return
|
|
|
|
val pendingIntent = PendingIntent.getActivity(
|
|
context, System.currentTimeMillis().toInt(), intent,
|
|
PendingIntent.FLAG_UPDATE_CURRENT or (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0)
|
|
)
|
|
|
|
val notificationBuilder = NotificationCompat.Builder(context, CHANNEL_ID)
|
|
.setSmallIcon(android.R.drawable.ic_dialog_info)
|
|
.setContentTitle(title)
|
|
.setContentText(body)
|
|
.setAutoCancel(true)
|
|
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
|
.setDefaults(NotificationCompat.DEFAULT_ALL)
|
|
.setNumber(totalCount)
|
|
.setContentIntent(pendingIntent)
|
|
|
|
notificationManager.notify(finalNotificationId, notificationBuilder.build())
|
|
}
|
|
}
|