lukertaylor

Expo notifications handlers

Aug 1st, 2025 (edited)
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 3.90 KB | Source Code | 0 0
  1. import { useEffect } from 'react';
  2. import { Platform, Text } from 'react-native';
  3. import * as Notifications from 'expo-notifications';
  4. import * as Device from 'expo-device';
  5. import Constants from 'expo-constants';
  6. import * as TaskManager from 'expo-task-manager';
  7. import { SafeAreaView } from 'react-native-safe-area-context';
  8.  
  9. const BACKGROUND_NOTIFICATION_TASK = 'BACKGROUND-NOTIFICATION-TASK';
  10.  
  11. TaskManager.defineTask<Notifications.NotificationTaskPayload>(
  12.   BACKGROUND_NOTIFICATION_TASK,
  13.   async ({ data, error, executionInfo }) => {
  14.     if (error) {
  15.       console.error('❌ Error in background task:', error);
  16.       return;
  17.     }
  18.  
  19.     console.log('📬 Background notification task received!');
  20.     console.log('Data:', JSON.stringify(data, null, 2));
  21.     console.log('Execution Info:', JSON.stringify(executionInfo, null, 2));
  22.  
  23.     // You can add async logic here if needed (e.g., fetch(), store data)
  24.   }
  25. );
  26.  
  27. Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK);
  28.  
  29. Notifications.setNotificationHandler({
  30.   handleNotification: async () => ({
  31.     shouldPlaySound: true,
  32.     shouldSetBadge: true,
  33.     shouldShowBanner: true,
  34.     shouldShowList: true
  35.   })
  36. });
  37.  
  38. export default function RootLayout() {
  39.   useEffect(() => {
  40.     registerForPushNotificationsAsync()
  41.       .then((token) => console.log(`Token: ${token}`))
  42.       .catch((error: any) => console.log(`Error: ${error}`));
  43.   }, []);
  44.  
  45.   useEffect(() => {
  46.     const responseListener =
  47.       Notifications.addNotificationResponseReceivedListener((response) => {
  48.         console.log('Notification response listener:');
  49.         console.log(JSON.stringify(response, null, 2));
  50.       });
  51.  
  52.     return () => {
  53.       responseListener.remove();
  54.     };
  55.   }, []);
  56.  
  57.   useEffect(() => {
  58.     let isMounted = true;
  59.  
  60.     Notifications.getLastNotificationResponseAsync().then((response) => {
  61.       if (!isMounted || !response?.notification) {
  62.         return;
  63.       }
  64.       console.log('Last notification response:');
  65.       console.log(JSON.stringify(response, null, 2));
  66.     });
  67.     Notifications.clearLastNotificationResponse();
  68.  
  69.     return () => {
  70.       isMounted = false;
  71.     };
  72.   }, []);
  73.  
  74.   return (
  75.     <SafeAreaView
  76.       style={{
  77.         flex: 1,
  78.         alignItems: 'center',
  79.         justifyContent: 'center',
  80.         backgroundColor: 'white'
  81.       }}
  82.     >
  83.       <Text>Home Page</Text>
  84.     </SafeAreaView>
  85.   );
  86. }
  87.  
  88. function handleRegistrationError(errorMessage: string) {
  89.   alert(errorMessage);
  90.   throw new Error(errorMessage);
  91. }
  92.  
  93. async function registerForPushNotificationsAsync(): Promise<
  94.   string | undefined
  95. > {
  96.   if (Platform.OS === 'android') {
  97.     Notifications.setNotificationChannelAsync('default', {
  98.       name: 'default',
  99.       importance: Notifications.AndroidImportance.MAX,
  100.       vibrationPattern: [0, 250, 250, 250],
  101.       lightColor: '#FF231F7C'
  102.     });
  103.   }
  104.  
  105.   if (Device.isDevice) {
  106.     const { status: existingStatus } =
  107.       await Notifications.getPermissionsAsync();
  108.     let finalStatus = existingStatus;
  109.     if (existingStatus !== 'granted') {
  110.       const { status } = await Notifications.requestPermissionsAsync();
  111.       finalStatus = status;
  112.     }
  113.     if (finalStatus !== 'granted') {
  114.       handleRegistrationError(
  115.         'Permission not granted to get push token for push notification!'
  116.       );
  117.       return;
  118.     }
  119.     const projectId =
  120.       Constants?.expoConfig?.extra?.eas?.projectId ??
  121.       Constants?.easConfig?.projectId;
  122.     if (!projectId) {
  123.       handleRegistrationError('Project ID not found');
  124.       return;
  125.     }
  126.     try {
  127.       const pushTokenString = (
  128.         await Notifications.getExpoPushTokenAsync({
  129.           projectId
  130.         })
  131.       ).data;
  132.       return pushTokenString;
  133.     } catch (e: unknown) {
  134.       handleRegistrationError(`${e}`);
  135.     }
  136.   } else {
  137.     handleRegistrationError('Must use physical device for push notifications');
  138.   }
  139. }
  140.  
Advertisement
Add Comment
Please, Sign In to add comment