differentiate between button clicks using pending intent - android

I am showing a custom notification (FCM). custom notification has two buttons approve and deny.
I have managed to create pending intent and a broadcast receiver and now I know in onReceive when the button is clicked.
How can i differentiate between button clicks in onReceive, I tried to pass extras on the intent, but intent.getStringExtra("clicked") gave me null value.
what is the right way of knowing which button is clicked approve , deny
This is the code I tried.
Thanks for your help in advance
R
override fun onMessageReceived(message: RemoteMessage) {
Log.d("FCMService", "onMessageReceived START ${isAppOnForeground()}")
if(!isAppOnForeground()) {
val notificationLayout = RemoteViews(
packageName,
R.layout.plugin_requires_approval_notification_small
)
val notificationLayoutExpanded = RemoteViews(
packageName,
R.layout.plugin_requires_approval_notification_large
)
val title = message.data[MSG_TITLE]
val subTitle = message.data[MSG_SUB_TITLE]
notificationLayout.setTextViewText(R.id.tvTitle, title)
notificationLayout.setTextViewText(R.id.tvSubTitle, subTitle)
notificationLayoutExpanded.setTextViewText(R.id.tvTitle, title)
notificationLayoutExpanded.setTextViewText(R.id.tvSubTitle, subTitle)
// Apply the layouts to the notification
val customNotification = NotificationCompat.Builder(
this,
CarInfoProcessingService.NOTIFICATION_CHANNEL_ID
)
.setSmallIcon(R.mipmap.ic_launcher)
.setStyle(NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(notificationLayout)
.setCustomBigContentView(notificationLayoutExpanded)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.build()
val switchIntent = Intent(this, SwitchButtonListener::class.java)
switchIntent.putExtra("clicked", "btnApprove")
val pendingSwitchIntent = PendingIntent.getBroadcast(
this, 0,
switchIntent, 0
)
//TWO BUTTONS WITH SAME PENDING SWITCH INTENT
notificationLayoutExpanded.setOnClickPendingIntent(R.id.btnApprove, pendingSwitchIntent)
notificationLayoutExpanded.setOnClickPendingIntent(R.id.btnDeny, pendingSwitchIntent)
val notificationManager =
getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0, customNotification)
}
Log.d("FCMService", "onMessageReceived END")
}
class SwitchButtonListener : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Log.d("fcmService", "onReceive ${intent.getStringExtra("clicked")}")
}
}
Manifest
<receiver android:name=".messaging.FcmService$SwitchButtonListener" android:exported="true">
<intent-filter>
<action android:name="Button_Clicked"/>
</intent-filter>
</receiver>
EDIT : Updated code that might help others
override fun onMessageReceived(message: RemoteMessage) {
Log.d("FCMService", "onMessageReceived START ${isAppOnForeground()}")
if(!isAppOnForeground()) {
val notificationLayout = RemoteViews(
packageName,
R.layout.plugin_requires_approval_notification_small
)
val notificationLayoutExpanded = RemoteViews(
packageName,
R.layout.plugin_requires_approval_notification_large
)
val title = message.data[MSG_TITLE]
val subTitle = message.data[MSG_SUB_TITLE]
notificationLayout.setTextViewText(R.id.tvTitle, title)
notificationLayout.setTextViewText(R.id.tvSubTitle, subTitle)
notificationLayoutExpanded.setTextViewText(R.id.tvTitle, title)
notificationLayoutExpanded.setTextViewText(R.id.tvSubTitle, subTitle)
// Apply the layouts to the notification
val customNotification = NotificationCompat.Builder(
this,
CarInfoProcessingService.NOTIFICATION_CHANNEL_ID
)
.setSmallIcon(R.mipmap.ic_launcher)
.setStyle(NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(notificationLayout)
.setCustomBigContentView(notificationLayoutExpanded)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.build()
val approveIntent = Intent(this, CustomNotificationListener::class.java)
approveIntent.putExtra("onClickListener", "approve")
val pendingApproveIntent = PendingIntent.getBroadcast(
this,
0,
approveIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
notificationLayoutExpanded.setOnClickPendingIntent(R.id.btnApprove, pendingApproveIntent)
val denyIntent = Intent(this, CustomNotificationListener::class.java)
denyIntent.putExtra("onClickListener", "deny")
val pendingDenyIntent = PendingIntent.getBroadcast(
this,
1,
denyIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
notificationLayoutExpanded.setOnClickPendingIntent(R.id.btnDeny, pendingDenyIntent)
val notificationManager =
getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0, customNotification)
}
Log.d("FCMService", "onMessageReceived END")
}
class CustomNotificationListener : BroadcastReceiver() {
#Inject
lateinit var chargeSessionRepo: ChargeSessionRepository
private var lastChargeStatus: ChargeStatusDTO? = null
override fun onReceive(context: Context, intent: Intent) {
Log.d("fcmService", "onReceive ${intent.getStringExtra("onClickListener")}")
when(intent.getStringExtra("onClickListener")) {
"approve" -> {
}
"deny" -> {
}
}
}
}

You need to use two distinct, up-to-date PendingIntent objects, wrapped around different Intent objects (e.g., ones with differing extras).
For "distinct", you need the IDs of the PendingIntent objects to be different. The ID is the second parameter to the PendingIntent.getBroadcast() call.
For "up-to-date", you need to update any existing PendingIntent that your code might have created previously. For that, pass PendingIntent.FLAG_UPDATE_CURRENT as the fourth parameter to the PendingIntent.getBroadcast() call.

Related

How to cancel a scheduled local notification in Kotlin?

I have an app where the user creates its own local notifications. User declares name, date and time the nofication should popup and specifies the repeating frequency.
Then the notifications are listed in a recyclerview in another fragment.
The user is able to delete notification by swiping its recyclerview item to the left.
But when I create a notification, delete it then it still pops up at the specified time.
I am storing the notificationID in SharedPreferences as a date when its created (so that I can store it in my DB). I am passing it as a string with putExtra to my BroadcastReceiver class, I am getting the notificationID as a String in my BroadcastReceiver class with getStringExtra. Then passing the same notificationID.toInt() to my pendingIntent.getActivity. Then in my Fragment with recyclerView I am passing the same notificationID for cancelling and it still doesn't cancel.
Perhaps I'm using wrong flags?
Thanks a lot for any help.
Here's my BroadcastReceiver class:
const val titleExtra = "titleExtra"
const val descriptionExtra = "descriptionExtra"
val notificationID = "notificationID"
class Notification: BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val intentToRepeat = Intent(context, MainActivity::class.java)
val id = intent.getStringExtra(notificationID).toString()
val pendingIntent = PendingIntent.getActivity(context, id.toInt(), intentToRepeat, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
val notification = NotificationCompat.Builder(context, channelID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(intent.getStringExtra(titleExtra))
.setContentText(intent.getStringExtra(descriptionExtra))
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.build()
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (intent.action == "cancel") {
manager.cancel(id.toInt())
}
else {
manager.notify(id.toInt(), notification)
}
}
}
My AndroidManifest:
<receiver android:name=".powiadomienia.Powiadomienie" android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="cancel"/>
<action android:name="create" />
</intent-filter>
</receiver>
In my recyclerview with notifications listed:
val currentNotification: SetNotification = listAdapter.getNotificationByPosition(viewHolder.bindingAdapterPosition)
if(direction == ItemTouchHelper.LEFT) {
// CANCEL
//val manager = requireContext().getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
//manager.cancel(currentPowiadomienie.notificationId!!)
val alarmManager = requireActivity().getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(requireContext(), Notification::class.java)
intent.action = "cancel"
val pendingIntent = PendingIntent.getService(requireContext(), currentNotification.notificationId!!.toInt(), intent, PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE)
pendingIntent?.let { _pendingIntent ->
alarmManager.cancel(_pendingIntent)
}
Neither manager.cancel() nor alarmManager.cancel() works.
The notification creates but how to cancel it?!
I think you need to call notifydatasetchanged() method after the alarmManager.cancel() like this:
val currentNotification: SetNotification =
listAdapter.getNotificationByPosition(viewHolder.bindingAdapterPosition)
if(direction == ItemTouchHelper.LEFT) {
val alarmManager =
requireActivity().getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(requireContext(), Notification::class.java)
intent.action = "cancel"
val pendingIntent = PendingIntent.getService(requireContext(),
currentNotification.notificationId!!.toInt(), intent,
PendingIntent.FLAG_CANCEL_CURRENT or
PendingIntent.FLAG_IMMUTABLE)
pendingIntent?.let { _pendingIntent ->
alarmManager.cancel(_pendingIntent)
notifyDataSetChanged()
}
I've solved my issue for not canceling coming notifications:
I think I was passing the wrong context. Check if you're passing the right one
To cancel a notification:
private fun removeAlarm(id: Int){
val alarmManager = activity?.getSystemService(Context.ALARM_SERVICE) as AlarmManager
// Notification = BroadcastReceiver class
val intent = Intent(requireContext(), Notification::class.java)
val pendingIntent = PendingIntent.getBroadcast(requireContext(), id, intent, PendingIntent.FLAG_IMMUTABLE)
alarmManager.cancel(pendingIntent)
}

not receiving extras from custom notification

I have a custom notification which has two buttons, when I click the button it opens CustomNotificationListener and I pass some extras which I am able to receive in the CustomNotificationListener.
But if the user clicks on the notification and not on the buttons it will take the user to MainActivity and I am passing extras fcmService to the intent but when I look for extras in MainActivity it is always null.
val intent = Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
I have also tried flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP still do not get extras in MainActivity.
Could you suggest what can be the problem please.
This is the code for custom notification.
private fun showCustomPushNotification(message: RemoteMessage, chargerId: String, pushMessageType: PushMessageType) {
val notificationLayout = RemoteViews(
packageName,
R.layout.plugin_requires_approval_notification_small
)
val notificationLayoutExpanded = RemoteViews(
packageName,
R.layout.plugin_requires_approval_notification_large
)
val title = message.data[MSG_TITLE]
val subTitle = message.data[MSG_SUB_TITLE]
notificationLayout.setTextViewText(R.id.tvTitle, title)
notificationLayout.setTextViewText(R.id.tvSubTitle, subTitle)
notificationLayoutExpanded.setTextViewText(R.id.tvTitle, title)
notificationLayoutExpanded.setTextViewText(R.id.tvSubTitle, subTitle)
// val intent = Intent(this, MainActivity::class.java).apply {
// flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
// }
val intent = Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP
}
intent.putExtra("fcmService", "customNotification")
val pendingIntent: PendingIntent = PendingIntent.getActivity(
this, 0,
intent,
PendingIntent.FLAG_IMMUTABLE
)
val customNotification = NotificationCompat.Builder(
this,
CarInfoProcessingService.APPROVE_EACH_PLUGIN_NOTIFICATION_CHANNEL_ID
)
.setSmallIcon(R.mipmap.ic_launcher)
.setStyle(NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(notificationLayout)
.setCustomBigContentView(notificationLayoutExpanded)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_MAX)
.build()
val approveIntent = Intent(this, CustomNotificationListener::class.java)
approveIntent.putExtra("pushMessageType", "$pushMessageType")
approveIntent.putExtra("onClickListener", "approve")
approveIntent.putExtra("chargerId", chargerId)
val pendingApproveIntent = PendingIntent.getBroadcast(
this,
0,
approveIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
notificationLayoutExpanded.setOnClickPendingIntent(R.id.btnApprove, pendingApproveIntent)
val denyIntent = Intent(this, CustomNotificationListener::class.java)
denyIntent.putExtra("pushMessageType", "$pushMessageType")
denyIntent.putExtra("onClickListener", "deny")
denyIntent.putExtra("chargerId", chargerId)
val pendingDenyIntent = PendingIntent.getBroadcast(
this,
1,
denyIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
notificationLayoutExpanded.setOnClickPendingIntent(R.id.btnDeny, pendingDenyIntent)
val notificationManager =
getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(CustomNotificationListener.WHAT_NOTIFICATION_ID, customNotification)
}
MainActivity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = MainActivityBinding.inflate(layoutInflater)
setContentView(binding.root)
val fcmServiceExtra = intent.getStringExtra("fcmService")
Log.d("fcmExtra", "$fcmServiceExtra")
Please suggest
thanks a lot in advance
R
Setting some unique dummy action to intent might help :
val notificationId = getNotificationId()
intent.action = "dummy_action $notificationId"
private fun getNotificationId(): Int {
return (1000 until 9000).random()
}
And for the flags i'm using like below:
intent.addFlags(
Intent.FLAG_ACTIVITY_NEW_TASK or
Intent.FLAG_ACTIVITY_CLEAR_TASK or
Intent.FLAG_ACTIVITY_CLEAR_TOP
)

Start Android Activity from notification and pass extra to it

I need to start an Activity from a Notification that I am creating in a FirebaseMessagingService. My problem is that I cannot pass custom action and extra to my ResultActivity in that case if ResultActivity is not in the stack and it is firstly created. In this case the ResultActivity get the intent with the android.intent.action.MAIN without the extra. Can somebody help what could be the problem, and how I can pass the notificationId extra to my Activity?
private fun sendNotification(remoteNotification: RemoteMessage.Notification, data: Map<String, String>) {
val notificationManager = NotificationManagerCompat.from(applicationContext)
createNotificationChannel(notificationManager)
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_text_info)
.setContentTitle(this.applicationInfo.loadLabel(packageManager).toString())
.setContentText(remoteNotification.body)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setAutoCancel(true)
.setContentIntent(
getNotificationContentItem(
data.getOrDefault(NOTIFICATION_DATA_KEY_NOTIFICATION_ID, NOTIFICATION_DATA_KEY_NOTIFICATION_ID)
)
)
.build()
notificationManager.notify(getRandomNotificationId(), notification)
}
private fun createNotificationChannel(notificationManager: NotificationManagerCompat) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH)
channel.description = CHANNEL_DESCRIPTION
notificationManager.createNotificationChannel(channel)
}
}
private fun getNotificationContentItem(notificationId: String): PendingIntent? {
val notificationIntent = Intent(this, ResultActivity::class.java)
notificationIntent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
notificationIntent.action = ACTION_START_NOTIFICATION_DETAILS
notificationIntent.putExtra(EXTRA_NAME_NOTIFICATION_ID, notificationId)
var flags = PendingIntent.FLAG_CANCEL_CURRENT
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
flags = flags or PendingIntent.FLAG_IMMUTABLE
}
val builder = TaskStackBuilder.create(this)
val pendingIntent = builder.run {
addNextIntentWithParentStack(notificationIntent)
getPendingIntent(0, flags)
}
return pendingIntent
}

Kotlin - How can I receive an intent from a notification pending intent on an app that is in the background?

I have a set of notifications for a calling application that I want to trigger a specific intent once it is interacted with (i.e when 'Accept' is clicked, it opens the in-call fragment screen, or if a voicemail notification is clicked, that fragment is opened)
The problem I'm having with this is that, if the application is not in the foreground, these interactions will instead just launch the application to MainActivity without completing the intent.
From what I can tell by debugging, I can trigger onNewIntent in MainActivity, but setIntent(intent) appears to contain this intent data
Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x14400000 pkg=com.round2pos.phone cmp=com.round2pos.phone/.MainActivity (has extras) }
Which is the primary launcher action from the intent-filter of the MainActivity in my AndroidManifest.xml.
I've looked at a number of questions on this as well as the Android Docs and none of it appears to be helping me, including:
Add PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE to the PendingIntent
Include Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP in the resultIntent
Change android:launchMode to singleTask or singleTop
Set setFullscreenIntent with a High Priority on the notification
None of these have been successful in allowing me to move the interaction to the proper fragment, I'd appreciate some help or guidance in the right direction.
Here's my NotificationService.kt where I create the notification and send the intent
val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH)
channel.description = "Phone Notifications"
channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
channel.enableVibration(true)
channel.setShowBadge(true)
channel.canShowBadge()
channel.shouldVibrate()
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
val tapResultIntent = Intent(applicationContext, MainActivity::class.java)
tapResultIntent.action = intent?.action
tapResultIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
val stackBuilder = TaskStackBuilder.create(applicationContext)
stackBuilder.addParentStack(MainActivity::class.java)
stackBuilder.addNextIntent(tapResultIntent)
val pendingIntent: PendingIntent = PendingIntent.getActivity(
applicationContext,
NOTIFICATION_ID,
tapResultIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val notificationBuilder = Notification.Builder(applicationContext, CHANNEL_ID!!)
.setContentTitle(notificationTitle)
.setContentText(notificationBody)
// .setContentIntent(pendingIntent)
.setShowWhen(true)
.setSmallIcon(notificationIcon!!)
.setChannelId(CHANNEL_ID)
.setCategory(Notification.CATEGORY_MISSED_CALL)
.setAutoCancel(true)
.setOngoing(false)
.setColor(Color.rgb(214, 10, 37))
.setFullScreenIntent(pendingIntent, true)
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build())
And my MainActivity.kt where I accept the intent
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
when (intent.action) {
ACTION_MISSED_CALL -> {
handleNewNotification(intent)
}
ACTION_NEW_VOICEMAIL -> {
handleNewNotification(intent)
}
else -> {
handleIncomingCallIntent(intent)
}
}
}
private fun handleNewNotification(intent: Intent) {
setUpNavigationBar()
when (intent.action) {
ACTION_MISSED_CALL -> {
val historyFragment = HistoryFragment()
navController.navigate(R.id.historyFragment)
}
ACTION_NEW_VOICEMAIL -> {
navController.navigate(R.id.voicemailFragment)
}
}
}
private fun handleIncomingCallIntent(intent: Intent?) {
val action = intent?.action
activeCallInvite = intent?.getParcelableExtra(INCOMING_CALL_INVITE)
callerID = intent?.getStringExtra(CALLER_ID)
callerIDNumber = intent?.getStringExtra(CALLER_ID_NUMBER).toString()
activeCallNotificationId = intent!!.getIntExtra(INCOMING_CALL_NOTIFICATION_ID, 0)
when (action) {
ACTION_INCOMING_CALL -> handleIncomingCall(activeCallInvite, activeCallNotificationId)
ACTION_INCOMING_CALL_NOTIFICATION -> Log.d(TAG, "INCOMING CALL ${activeCallInvite?.callerInfo}")
ACTION_CANCEL_CALL -> endForeground()
ACTION_FCM_TOKEN -> registerForCallInvites()
ACTION_ACCEPT -> answer()
else -> {
}
}
}

Notification works in Activity but not in Service

I am trying to integrate Firebase Cloud Messages into my app. The code I used in the showNotification function is from the Android User Interface Samples. I tried it in the Activity and it worked but am not sure why it's not working in the service. The println is showing the function is getting called and values are coming as expected. Is there anything am missing from the function?
class MessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
if (remoteMessage.data.isNotEmpty()) {
val message = Gson().fromJson(remoteMessage.data.toString(), Message.Res::class.java).payload!!
showNotification(message.title, message.body, message.count)
}
}
private fun showNotification(title: String?, body: String?, count: Int = 0) {
println("_print::showNotification(title:$title, body:$body, count:$count)")
val mainPendingIntent = PendingIntent.getActivity(
applicationContext, BuildConfig.REQUEST_CODE,
Intent(applicationContext, MainActivity::class.java),
PendingIntent.FLAG_UPDATE_CURRENT
)
val builder = NotificationCompat.Builder(applicationContext, "channel_email_1")
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher_round))
.setContentIntent(mainPendingIntent)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setColor(ContextCompat.getColor(applicationContext, R.color.primary))
.setSubText(if (count > 1) "You have $count pending notifications" else title)
.setCategory(Notification.CATEGORY_EMAIL)
.setPriority(1)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
NotificationManagerCompat.from(applicationContext)
.notify(BuildConfig.NOTIFICATION_ID, builder.build())
}
}
Instead of
val mainPendingIntent = PendingIntent.getActivity(
applicationContext, BuildConfig.REQUEST_CODE,
Intent(applicationContext, MainActivity::class.java),
PendingIntent.FLAG_UPDATE_CURRENT
)
NotificationManagerCompat.from(applicationContext)
.notify(BuildConfig.NOTIFICATION_ID, builder.build())
I use:
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// Since android Oreo notification channel is needed.
setupChannels(notificationManager, builder)
// Create pending intent, mention the Activity which needs to be triggered
// when user clicks on notification.
val notificationId = Random.nextInt()
navigateToScreen(builder, notificationId)
val notification = builder.build()
notificationManager.notify(notificationId, notification)
}
private fun setupChannels(notificationManager: NotificationManager,
builder: NotificationCompat.Builder) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId = "channel_email_1"
val channel = NotificationChannel(channelId, "title",
NotificationManager.IMPORTANCE_DEFAULT).apply {
description = "body"
// Add other settings.
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
canShowBadge()
setShowBadge(true)
}
notificationManager.createNotificationChannel(channel)
builder.setChannelId(channelId)
}
}
private fun navigateToScreen(builder: NotificationCompat.Builder,
notificationId: Int) {
val intent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, notificationId, intent,
PendingIntent.FLAG_UPDATE_CURRENT)
builder.setContentIntent(pendingIntent)
}

Categories

Resources