Skip to content
All writing

May 15, 2021 · 1 min read

Simple local push notifications in React Native (Android)

A minimal recipe for getting react-native-push-notification working on Android, including channel creation, scheduling, and cancellation.

#react-native#android

Want local push notifications to work? Steps:

  1. Create a file, e.g. AndroidNotificationHandler.js.

  2. Import the package:

import PushNotification, { Importance } from 'react-native-push-notification'
  1. Create a channel (required in modern versions):
const createChannel = () => {
  PushNotification.createChannel(
    {
      channelId: 'channel-id',
      channelName: 'My channel',
      channelDescription: 'A channel to categorise your notifications',
      playSound: false,
      soundName: 'default',
      importance: Importance.HIGH,
      vibrate: true,
    },
    (created) => console.log(`createChannel returned '${created}'`),
  )
}
  1. Schedule notifications:
const notificationHandler = (title, message, date) => {
  PushNotification.localNotificationSchedule({
    channelId: 'channel-id',
    title,
    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,
  })
}
  1. Cancel notifications:
const cancelNotifications = () => {
  PushNotification.cancelAllLocalNotifications()
}
  1. Export and use:
export { createChannel, notificationHandler, cancelNotifications }
const alertDescription = `Time to study ${topicName}`
notificationHandler('Reminder!', alertDescription, date)