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:
-
Create a file, e.g.
AndroidNotificationHandler.js. -
Import the package:
import PushNotification, { Importance } from 'react-native-push-notification'- 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}'`),
)
}- 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,
})
}- Cancel notifications:
const cancelNotifications = () => {
PushNotification.cancelAllLocalNotifications()
}- Export and use:
export { createChannel, notificationHandler, cancelNotifications }const alertDescription = `Time to study ${topicName}`
notificationHandler('Reminder!', alertDescription, date)