简体   繁体   中英

Alert and sound is not working in expo push notification

I'm developing an application using expo. I want to send and receive push notifications in my application using expo-notifications. I have integrated the expo-notification and I'm receiving the notification successfully but WITHOUT sound and popup alert. I always have to scroll down the notification panel and then only can see the notification. This is my code for registering for notification

async function registerForPushNotificationsAsync() {
    let token;
    if (Constants.isDevice) {
        const { status: existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
        let finalStatus = existingStatus;
        if (existingStatus !== 'granted') {
            const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
            finalStatus = status;
        }
        if (finalStatus !== 'granted') {
            alert('Failed to get push token for push notification!');
            return;
        }
        token = (await Notifications.getExpoPushTokenAsync()).data;
        console.log(token);
    } else {
        alert('Must use physical device for Push Notifications');
    }

    if (Platform.OS === 'android') {
        Notifications.setNotificationChannelAsync('default', {
            name: 'default',
            importance: Notifications.AndroidImportance,
            vibrationPattern: [0, 250, 250, 250],
            lightColor: '#FF231F7C',
        });
    }
    return token;
}

And this is my UseEffect where I'm registering and listening for notifications

useEffect(() => {
    _gettingRestaurants();

    registerForPushNotificationsAsync().then(token => setExpoPushToken(token));

    // This listener is fired whenever a user taps on or interacts with a notification (works when app is foregrounded, backgrounded, or killed)
    Notifications.addNotificationReceivedListener((notification)=>{
        alert(notification);
    });
    Notifications.addNotificationResponseReceivedListener((response)=>{
        alert(response);
    });
    
}, [isDataFetched])

One more thing, these listeners are also not working. I'm not seeing any alert from these two alerts. Please help me out.

Thank you!!!

For the listeners to work, try:

Add this in your app.json

{
  "expo": {
    ...
    "android": {
      ...
      "useNextNotificationsApi": true,
    }
  }
}

It didn't work at first for me, but after specifying the permissions, it worked:

{
  "expo": {
    ...
    "android": {
      ...
      "useNextNotificationsApi": true,
      "permissions": ["RECEIVE_BOOT_COMPLETED"]
    }
  }
}
      

And, if it doesn't work (it didn't for my Main project but did it for another one), you can try to use the legacy notification system that uses addListener :

import * as Notifications from 'expo-notifications';
import { Notifications as Notifications2 } from 'expo';

Notifications.addNotificationReceivedListener((notification) => {
  // New Notifications. Didn't work sometimes
});

Notifications2.addListener((data) => {
  // Legacy notifications. You get a deprecation warning, but works when the new Notifications don't
});

Also check if this helps you to get notifications when app is closed on in the background (just after Notification import)

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: false,
  }),
});

To get notifications with sound: If you expect them while the app is in the background, you need to define the setNotificationHandler with shouldPlaySound: true . You also need to specify in the notification that you want to play sound like so:

const message = {
    to: expoPushToken,
    sound: 'default', // <== the values are 'default' (sound) or null (silent)
    title: 'Original Title',
    body: 'And here is the body!',
    data: { data: 'goes here' },
  };

I remember there is also an option to set the priority of the notification. Play with those values until you get what you need. Search "priority" in this page: https://docs.expo.io/versions/latest/sdk/notifications/

for me, I face the same problem and no one of the solutions above worked for me. the problem occurs only when I set the sound as default like this

      content: {
        title: "Some title",
        body: "Some body",
        sound: "default",
      }

and it was working perfect on ios, but on android the popup notification and sound not showing at all, so I ended up setting the default only for ios and null for android and I got it to work fine like example below:

      content: {
        title: "Some title",
        body: "Some body",
        sound: Platform.OS === "android" ? null : "default",
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM