I have an app which uses notifications and everything is working fine below android 12 but on android 13 doesn't show the notifications. I have also added notification permissions but I can't figure out what is wrong any suggestions would be really appreciated.
Here is my code
Manifest
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
AlarmReceiver.kt
class AlarmReceiver : BroadcastReceiver() {
private val CHANNEL_ID = "1"
private val CHANNEL_NAME = "Notifications"
override fun onReceive(context: Context?, intent: Intent?) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT)
channel.description = context!!.getString(R.string.app_name)
channel.enableLights(true)
channel.enableVibration(true)
channel.lightColor = Color.BLUE
channel.setShowBadge(true)
channel.lockscreenVisibility = NotificationCompat.VISIBILITY_PUBLIC
val notificationManager = context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
val quote = runBlocking {
generateQuoteNotification(context!!)
}
// Create an Intent for the activity you want to start
val newIntent = Intent(context, MainActivity::class.java).apply {
putExtra(Constants.STRING_EXTRA_INCOMING_FRAGMENT, Constants.ACTIVITY_NOTIFICATION)
putExtra(Constants.STRING_EXTRA_QUOTE, quote)
}
// Create the TaskStackBuilder
val resultPendingIntent: PendingIntent? = TaskStackBuilder.create(context).run {
// Add the intent, which inflates the back stack
addNextIntentWithParentStack(newIntent)
// Get the PendingIntent containing the entire back stack
getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
}
// Build Notification
val builder = NotificationCompat.Builder(context!!, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_favorite)
.setColor(context.resources.getColor(R.color.teal_700,null))
.setContentTitle(context.getString(R.string.app_name))
.setContentText(quote)
.setContentIntent(resultPendingIntent) // On Notification Click Goto DetailActivity
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true)
with(NotificationManagerCompat.from(context)) {
// notificationId is a unique int for each notification that you must define
if (ActivityCompat.checkSelfPermission(context.applicationContext,
Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED ) {
context.showToast("Please grant Notification permission from App Settings")
return
}
notify(1, builder.build())
}
}
private suspend fun generateQuoteNotification(context: Context):
String = withContext(Dispatchers.IO) {
val db = AppDatabase.getDatabase(context).quoteDao()
db.generateNotification().quote
}
}
And here is my MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.appBarMain.toolbar)
checkNotificationPermission()
createNotification()
drawerLayout = binding.drawerLayout
val navView: NavigationView = binding.navView
val navHostFragment =
supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
navController = navHostFragment.navController
appBarConfiguration = AppBarConfiguration(navController.graph, drawerLayout)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
}
private fun checkNotificationPermission() {
// Sets up permissions request launcher.
val requestPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
if (isGranted) {
// Permission is granted. Continue the action or workflow in your app.
createNotification()
showToast("permission is granted -- requestPermissionLauncher")
} else {
Snackbar.make(findViewById(android.R.id.content),
"Please grant Notification permission from App Settings",
Snackbar.LENGTH_LONG
).show()
}
}
when {
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) ==
PackageManager.PERMISSION_GRANTED -> {
Log.e(TAG, "User accepted the notifications!")
createNotification()
}
shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS) -> {
Snackbar.make(findViewById(android.R.id.content),
"The user denied the notifications ):",
Snackbar.LENGTH_LONG
)
.setAction("Settings") {
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val uri: Uri =
Uri.fromParts("package", packageName, null)
intent.data = uri
startActivity(intent)
}
.show()
}
else -> {
requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
}
}
}
override fun onSupportNavigateUp(): Boolean {
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
private fun createNotification() {
val intent = Intent(this, AlarmReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(this,
0, intent, PendingIntent.FLAG_IMMUTABLE)
val alarms = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val calendar = Calendar.getInstance()
// val now = Calendar.getInstance()
calendar.set(Calendar.HOUR_OF_DAY, 8)
calendar.set(Calendar.MINUTE, 5)
// if (now.after(calendar)) {
// calendar.add(Calendar.DATE, 1)
// }
alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.timeInMillis,
AlarmManager.INTERVAL_DAY, pendingIntent)
}
}
P.S I don't have a physical device to test on so i'm using emulator