Created
July 26, 2020 04:55
-
-
Save sprejjs/a401dbee82fbf54874cf9074ed7a6cce to your computer and use it in GitHub Desktop.
Custom firebase messaging service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.spreys.pushnotifications | |
import android.app.NotificationChannel | |
import android.app.NotificationManager | |
import android.app.PendingIntent | |
import android.content.Context | |
import android.content.Intent | |
import android.media.RingtoneManager | |
import android.os.Build | |
import androidx.core.app.NotificationCompat | |
import com.google.firebase.messaging.FirebaseMessagingService | |
import com.google.firebase.messaging.RemoteMessage | |
class MyFirebaseMessagingService: FirebaseMessagingService() { | |
override fun onMessageReceived(remoteMessage: RemoteMessage) { | |
super.onMessageReceived(remoteMessage) | |
remoteMessage.notification?.title?.let { title -> | |
remoteMessage.notification?.body?.let { body -> | |
sendNotification(title, body) | |
} | |
} | |
} | |
private fun sendNotification(title: String, body: String) { | |
val intent = Intent(this, MainActivity::class.java) | |
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) | |
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT) | |
val channelId = "default" | |
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) | |
val notificationBuilder = NotificationCompat.Builder(this, channelId) | |
.setSmallIcon(R.mipmap.ic_launcher_round) | |
.setContentTitle(title) | |
.setContentText(body) | |
.setAutoCancel(true) | |
.setSound(defaultSoundUri) | |
.setContentIntent(pendingIntent) | |
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { | |
val channel = NotificationChannel(channelId, "Channel title", NotificationManager.IMPORTANCE_DEFAULT) | |
notificationManager.createNotificationChannel(channel) | |
} | |
notificationManager.notify(0, notificationBuilder.build()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment