Roxy_45

Notification_mag

Feb 27th, 2024
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 2.32 KB | None | 0 0
  1. private fun createNotificationChannel() {
  2.         val name = "Re"
  3.         val descriptionText = "Yours Good"
  4.         val importance = NotificationManager.IMPORTANCE_DEFAULT
  5.         val channel = NotificationChannel(NOTIFICATION_CHANNEL_ID, name, importance).apply {
  6.             description = descriptionText
  7.         }
  8.         val notificationManager: NotificationManager =
  9.             getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
  10.         notificationManager.createNotificationChannel(channel)
  11.     }
  12.  
  13. private fun checkPermissionsAndShowNotification(score: Int) {
  14.         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
  15.             if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
  16.                 ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), POST_NOTIFICATIONS_REQUEST_CODE)
  17.             } else {
  18.                 showNotification(score)
  19.             }
  20.         } else {
  21.             showNotification(score)
  22.         }
  23.     }
  24.  
  25. @SuppressLint("MissingPermission")
  26.     private fun showNotification(score: Int) {
  27.         createNotificationChannel() // Ensure the channel is created before showing a notification
  28.         val builder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
  29.             .setSmallIcon(R.drawable.images) // Ensure you have a drawable named `images` in your drawable resources
  30.             .setContentTitle(" Result")
  31.             .setContentText("You $s") // Incorporate the score into the notification text
  32.             .setPriority(NotificationCompat.PRIORITY_DEFAULT)
  33.         with(NotificationManagerCompat.from(this)) {
  34.             notify(1, builder.build()) // The first parameter is a unique ID for the notification
  35.         }
  36.     }
  37.  
  38. override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
  39.         super.onRequestPermissionsResult(requestCode, permissions, grantResults)
  40.         if (requestCode == POST_NOTIFICATIONS_REQUEST_CODE && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  41.             showNotification(tempScore) // Use tempScore here
  42.         } else {
  43.             Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show()
  44.         }
  45.     }
Tags: #kotlin
Advertisement
Add Comment
Please, Sign In to add comment