|
| 1 | +package com.example.redconefinal |
| 2 | + |
| 3 | +import android.app.Notification |
| 4 | +import android.app.NotificationChannel |
| 5 | +import android.app.NotificationManager |
| 6 | +import android.app.PendingIntent |
| 7 | +import android.content.Context |
| 8 | +import android.content.Intent |
| 9 | +import android.os.Build |
| 10 | +import android.util.Log |
| 11 | +import androidx.core.app.NotificationCompat |
| 12 | +import com.google.firebase.messaging.FirebaseMessagingService |
| 13 | +import com.google.firebase.messaging.RemoteMessage |
| 14 | + |
| 15 | +class FirebaseMsgService : FirebaseMessagingService() { |
| 16 | + private val CHANNEL_ID = "push_noti" |
| 17 | + |
| 18 | + override fun onNewToken(token: String) { |
| 19 | + super.onNewToken(token) |
| 20 | + Log.d("FirebaseMsgService", "Refreshed token: $token") |
| 21 | + } |
| 22 | + |
| 23 | + override fun onMessageReceived(remoteMessage: RemoteMessage) { |
| 24 | + super.onMessageReceived(remoteMessage) |
| 25 | + Log.d("FirebaseMsgService", "Message received: ${remoteMessage.data}") |
| 26 | + |
| 27 | + remoteMessage.notification?.let { |
| 28 | + Log.d("FirebaseMsgService", "Notification Title: ${it.title}, Body: ${it.body}") |
| 29 | + pushNotification(it.title, it.body) |
| 30 | + } ?: Log.d("FirebaseMsgService", "No notification payload") |
| 31 | + } |
| 32 | + |
| 33 | + private fun pushNotification(title: String?, msg: String?) { |
| 34 | + val nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager? |
| 35 | + |
| 36 | + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { |
| 37 | + val name = "Custom Channel" |
| 38 | + val descriptionText = "Channel for Push Notifications" |
| 39 | + val importance = NotificationManager.IMPORTANCE_HIGH |
| 40 | + val channel = NotificationChannel(CHANNEL_ID, name, importance).apply { |
| 41 | + description = descriptionText |
| 42 | + } |
| 43 | + nm?.createNotificationChannel(channel) |
| 44 | + } |
| 45 | + |
| 46 | + val intent = Intent(this, MainActivity::class.java).apply { |
| 47 | + addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) |
| 48 | + } |
| 49 | + val pendingIntent = PendingIntent.getActivity(this, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) |
| 50 | + |
| 51 | + val notification: Notification = NotificationCompat.Builder(this, CHANNEL_ID) |
| 52 | + .setSmallIcon(R.drawable.rc1) |
| 53 | + .setContentTitle(title) |
| 54 | + .setContentText(msg) |
| 55 | + .setPriority(NotificationCompat.PRIORITY_HIGH) |
| 56 | + .setContentIntent(pendingIntent) |
| 57 | + .setAutoCancel(true) |
| 58 | + .build() |
| 59 | + |
| 60 | + val notificationId = 1 |
| 61 | + nm?.notify(notificationId, notification) |
| 62 | + } |
| 63 | +} |
0 commit comments