From Android 13, notifications won’t work until and unless we have not taken runtime permission from the user. Without this permission, the user won’t be able to receive any kind of notification to their devices.
Open the AndroidManifest.xml and add the following permission to it.
1 |
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/> |
Now we have to add runtime permission at the code level similarly we do for Camera, Contacts, Storage, etc permissions. The below code will show a permission dialog whenever we request the POST_NOTIFICATIONS permission.
Based on user consent the notifications will be shown to them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
@RequiresApi(Build.VERSION_CODES.TIRAMISU) private fun checkNotificationPermission() { val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { isGranted: Boolean -> if (isGranted) { // Permission is granted. Continue the action or workflow in your // app. } else { // Permission is denied. Explain user why you need this permission // and ask the permission again if user provide consent } } when { ContextCompat.checkSelfPermission( this, android.Manifest.permission.POST_NOTIFICATIONS ) == PackageManager.PERMISSION_GRANTED -> { // Notification permission is granted } ActivityCompat.shouldShowRequestPermissionRationale( this, android.Manifest.permission.POST_NOTIFICATIONS ) -> { // user denied the permission - explain user why you need this permission } else -> { // ask for notification permission directly requestPermissionLauncher.launch( android.Manifest.permission.POST_NOTIFICATIONS ) } } } |
Using the above two steps will enable the notification in your app and users will be able to receive them only if they allow it.
Thanks
Subscribe to us and get the latest news.