My app uses a receiver to send the user notifications after a certain amount of time. The receiver works great as it runs a few functions, the notification however doesn't work so smoothly.
On the emulator (API29 and Android 10) it sends them correctly however when I install it on real devices it either doesn't work at all or works perfectly fine.
My phone had the notifications perfectly until when I updated it to android 12, from then on no notifications are fired. I also tested it on an older device (Android 7) and again it doesn't work.
I read into it and don't really understand how the channels work, so I think the issue might be there however I find it weird how it would then still work on some devices/emulators.
Here is my code:
class MyReceiver: BroadcastReceiver() {
@RequiresApi(Build.VERSION_CODES.O)
override fun onReceive(context: Context, intent: Intent) {
val notificationChannel =
NotificationChannel("My Channel", "New Quote",
NotificationManager.IMPORTANCE_DEFAULT).apply {
description = "Alerts when A new daily quote is set!"
}
val titles = arrayOf(
"Become inspired!",
"Check out this quote!",
"A new quote appeared!",
"Daily quote available!"
)
val title = titles.random()
val i = Intent(context, Qinperation::class.java)
val builder = NotificationCompat.Builder(context, "My Channel")
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle(title)
.setContentText("A new daily quote is available for viewing")
.setContentIntent(
PendingIntent.getActivity(
context,
0,
i,
PendingIntent.FLAG_UPDATE_CURRENT
)
);
with(NotificationManagerCompat.from(context)) {
createNotificationChannel(notificationChannel)
notify(1, builder.build())
}
}
}
All help is appreciated :)
This was my bad. Turns out that on certain devices (like the one I was testing on), Doesn't support the pending intent I was using to fire the notification. If people have a similar issue, try changing Pending Intents to - PendingIntent.FLAG_IMMUTABLE
as this works on more devices, Especially newer ones!