DEV Community

loading...

Simple way to get react-native local push notifications to work (android).

Usaid
Full Stack Developer
・2 min read

Do you want to get local push notifications to work? Here's simple steps that might help you:

1) Create a file name it anything you want I named it "AndroidNotificationHandler.js".

2) Import react-native push-notification package:

import PushNotification, {Importance} from 'react-native-push-notification';

Enter fullscreen mode Exit fullscreen mode

3) Since latest update push-notification package requires you to create a channel id in order for notifications to work properly, here's what it looks like:

const createChannel = () => {
  PushNotification.createChannel(
    {
      channelId: 'channel-id', // (required)
      channelName: 'My channel', // (required)
      channelDescription: 'A channel to categorise your notifications', // (optional) default: undefined.
      playSound: false, // (optional) default: true
      soundName: 'default', // (optional) See `soundName` parameter of `localNotification` function
      importance: Importance.HIGH, // (optional) default: Importance.HIGH. Int value of the Android notification importance
      vibrate: true, // (optional) default: true. Creates the default vibration patten if true.
    },
    (created) => console.log(`createChannel returned '${created}'`), // (optional) callback returns whether the channel was created, false means it already existed.
  );
};

Enter fullscreen mode Exit fullscreen mode

4) After you have created the channelId function create another function that will do the main work in order to get the notifications that you want it to get. Check this out:


const notificationHandler = (title, message, date) => {
  PushNotification.localNotificationSchedule({
    channelId: 'channel-id', // this we get from above func()
    title: title,
    message: message,
    autoCancel: true,
    subText: 'Notification',
    vibrate: true,
    vibration: 300,
    playSound: true,
    soundName: 'default',
    ignoreInForeground: false,
    importance: 'high',
    invokeApp: true,
    allowWhileIdle: true,
    priority: 'high',
    visibility: 'public',
    date: date,
  });
};
Enter fullscreen mode Exit fullscreen mode

5) You can also cancel notifications if you want, here's how:


const cancelNotifications = () => {
  PushNotification.cancelAllLocalNotifications();
};
Enter fullscreen mode Exit fullscreen mode

6) export your functions:

export {createChannel, notificationHandler, cancelNotifications};
Enter fullscreen mode Exit fullscreen mode

7) You can now import use these functions across your project, example from my project:

let alertDescription = `Time to study ${topicName}`;
notificationHandler('Reminder!', alertDescription, date);
// I get date parameter from datepicker.
Enter fullscreen mode Exit fullscreen mode

That is it. You shall get your notifications now :).

Discussion (0)