Files
rider-pro-android-app/app/src/main/java/com/aiosman/ravenow/MyFirebaseMessagingService.kt

94 lines
3.1 KiB
Kotlin
Raw Normal View History

2024-11-17 20:07:42 +08:00
package com.aiosman.ravenow
2024-09-05 22:04:41 +08:00
import android.Manifest
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
val MessageTypeLike = "like"
fun showLikeNotification(context: Context, title: String, message: String, postId: Int) {
val channelId = ConstVars.MOMENT_LIKE_CHANNEL_ID
// Create an Intent to open the specific activity
val intent = Intent(context, MainActivity::class.java).apply {
putExtra("POST_ID", postId.toString())
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
// Create a PendingIntent to wrap the Intent
val pendingIntent = PendingIntent.getActivity(
context,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val notificationBuilder = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.rider_pro_favoriate)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
with(NotificationManagerCompat.from(context)) {
if (ActivityCompat.checkSelfPermission(
context,
Manifest.permission.POST_NOTIFICATIONS
) != PackageManager.PERMISSION_GRANTED
) {
// 用户没有授权,不显示通知
return
}
notify(System.currentTimeMillis().toInt(), notificationBuilder.build())
}
}
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
Log.d("Pushing", "Refreshed token: $token")
super.onNewToken(token)
}
override fun onMessageReceived(remoteMessage: RemoteMessage) {
if (remoteMessage.data.containsKey("action")) {
when (remoteMessage.data["action"]) {
MessageTypeLike -> {
val postId = remoteMessage.data["postId"]?.toInt() ?: return
showLikeNotification(
applicationContext,
remoteMessage.data["title"] ?: "FCM Message",
remoteMessage.data["body"] ?: "No message body",
postId
)
}
else -> {
Log.w("Pushing", "Unknown message type: ${remoteMessage.data["messageType"]}")
}
}
}
super.onMessageReceived(remoteMessage)
}
fun prepareIntent(clickAction: String?): Intent {
val intent: Intent
val isAppInBackground: Boolean = !MainActivityLifecycle.isForeground
intent = if (isAppInBackground) {
Intent(this, MainActivity::class.java)
} else {
Intent(clickAction)
}
return intent
}
}