Search code examples
javascriptandroidreact-nativepermissions

How to ask for notifications permission on Android using react-native 0.68?


My project is running on react-native 0.68.5 and I can't upgrade it, is there a way to ask for notifications using this react native version?

Right now it's working with previous Android versions, but I want my app to ask for these kind of permissions on newer android versions.


Solution

  • You need past the below line in AndroidManifest.xml

    <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
    

    Create a function for request the permission by using below code.

    import { Platform,PermissionsAndroid } from 'react-native';
    
    const requestNotificationPermission = async () => {
      if(Platform.OS ==="android"){
        try {
          PermissionsAndroid.check('android.permission.POST_NOTIFICATIONS').then(
            response => {
              if(!response){
                PermissionsAndroid.request('android.permission.POST_NOTIFICATIONS',{
                    title: 'Notification',
                    message:
                      'App needs access to your notification ' +
                      'so you can get Updates',
                    buttonNeutral: 'Ask Me Later',
                    buttonNegative: 'Cancel',
                    buttonPositive: 'OK',
                })
              }
            }
          ).catch(
            err => {
              console.log("Notification Error=====>",err);
            }
          )
        } catch (err){
          console.log(err);
        }
      }
    };

    Call this requestNotificationPermission() function when you want to ask permission for Android Notification permission.