Earlier Android version we just need permission in Android Manifest file. But onwards Android 13 also need runtime permission. If user Allowed it then it will receive notifications otherwise it will not work. So, here is what we need to enable it and ask for permission.
First of all we will mention permission in Manifest file.
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
Code language: HTML, XML (xml)
Then we will add given below snippet it in code file.
For JAVA
private void requestNotificationPermission() {
ActivityResultLauncher<String> requestPermissionLauncher = registerForActivityResult(
new ActivityResultContracts.RequestPermission(),
isGranted -> {
if (isGranted) {
Log.d("DEBUG_TAG", "Notifications permission granted");
} else {
Snackbar.make(
mainLayout,
String.format(
"Notifications permission denied",
getString(R.string.app_name)
),
Snackbar.LENGTH_INDEFINITE
).setAction("Go to Settings", v -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
Intent settingsIntent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
startActivity(settingsIntent);
}
}).show();
}
}
);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS);
}
}
Code language: JavaScript (javascript)
For Kotlin
private fun requestNotificationPermission() {
val requestPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted ->
if (isGranted) {
Log.d("DEBUG_TAG", "Notifications permission granted")
} else {
Snackbar.make(
mainLayout,
"Notifications permission denied",
Snackbar.LENGTH_INDEFINITE
).setAction("Go to Settings") {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
val settingsIntent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
startActivity(settingsIntent)
}
}.show()
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
}
}
Code language: PHP (php)
Then call above function in your code
For JAVArequestNotificationPermission();
For KotlinrequestNotificationPermission()