Sunday, July 17, 2022

Android 12 Notification Permission

Notification permissions for apps targeting Android 12L (API level 32) or lower

Android automatically asks the user for permission the first time your app creates a notification channel, as long as the app is in the foreground. However, there are important caveats regarding the timing of channel creation and permission requests:


If your app creates its first notification channel when it is running in the background (which the FCM SDK does when receiving an FCM notification), Android will not allow the notification to be displayed and will not prompt the user for the notification permission until the next time your app is opened. This means that any notifications received before your app is opened and the user accepts the permission will be lost.

We strongly recommend that you update your app to target Android 13+ to take advantage of the platform’s APIs to request permission. If that is not possible, your app should create notification channels before you send any notifications to the app in order to trigger the notification permission dialog and ensure no notifications are lost. See notification permission best practices for more information. 

references:

https://firebase.google.com/docs/cloud-messaging/android/client

Android 13 - Notification Permissions

// Declare the launcher at the top of your Activity/Fragment:
private final ActivityResultLauncher<String> requestPermissionLauncher =
        registerForActivityResult
(new ActivityResultContracts.RequestPermission(), isGranted -> {
           
if (isGranted) {
               
// FCM SDK (and your app) can post notifications.
           
} else {
               
// TODO: Inform user that that your app will not show notifications.
           
}
       
});

// ...
private void askNotificationPermission() {
   
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) ==
           
PackageManager.PERMISSION_GRANTED) {
       
// FCM SDK (and your app) can post notifications.
   
} else if (shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS)) {
       
// TODO: display an educational UI explaining to the user the features that will be enabled
       
//       by them granting the POST_NOTIFICATION permission. This UI should provide the user
       
//       "OK" and "No thanks" buttons. If the user selects "OK," directly request the permission.
       
//       If the user selects "No thanks," allow the user to continue without notifications.
   
} else {
       
// Directly ask for the permission
        requestPermissionLauncher
.launch(Manifest.permission.POST_NOTIFICATIONS);
   
}
}

 https://firebase.google.com/docs/cloud-messaging/android/client