Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package acr.browser.lightning.fcm
- import acr.browser.lightning.MainActivity
- import acr.browser.lightning.R
- 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 android.util.Log
- import com.google.firebase.messaging.FirebaseMessagingService
- import com.google.firebase.messaging.RemoteMessage
- class MyFirebaseMessagingService : FirebaseMessagingService() {
- override fun onMessageReceived(remoteMessage: RemoteMessage) {
- Log.d(TAG, "From: ${remoteMessage?.from}")
- remoteMessage?.notification?.let {
- Log.d(TAG, "Message Notification Body: ${it.body}")
- sendNotification(it.title, it.body)
- }
- }
- override fun onNewToken(token: String) {
- Log.d(TAG, "Refreshed token: $token")
- sendRegistrationToServer(token)
- }
- private fun handleNow() {
- Log.d(TAG, "Short lived task is done.")
- }
- private fun sendRegistrationToServer(token: String?) {
- // TODO: Implement this method to send token to your app server.
- }
- 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 /* Request code */, intent,
- PendingIntent.FLAG_ONE_SHOT)
- val channelId = getString(R.string.default_notification_channel_id)
- val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
- val notificationBuilder = NotificationCompat.Builder(this, channelId)
- .setSmallIcon(R.drawable.ic_message_white_24dp)
- .setContentTitle(title)
- .setContentText(body)
- .setAutoCancel(true)
- .setSound(defaultSoundUri)
- .setContentIntent(pendingIntent)
- val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
- // Since android Oreo notification channel is needed.
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- val channel = NotificationChannel(channelId,
- "Channel human readable title",
- NotificationManager.IMPORTANCE_DEFAULT)
- notificationManager.createNotificationChannel(channel)
- }
- notificationManager.notify(0 /* ID of notification */, notificationBuilder.build())
- }
- companion object {
- private const val TAG = "MyFirebaseMsgService"
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement