Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { useEffect } from 'react';
- import { Platform, Text } from 'react-native';
- import * as Notifications from 'expo-notifications';
- import * as Device from 'expo-device';
- import Constants from 'expo-constants';
- import * as TaskManager from 'expo-task-manager';
- import { SafeAreaView } from 'react-native-safe-area-context';
- const BACKGROUND_NOTIFICATION_TASK = 'BACKGROUND-NOTIFICATION-TASK';
- TaskManager.defineTask<Notifications.NotificationTaskPayload>(
- BACKGROUND_NOTIFICATION_TASK,
- async ({ data, error, executionInfo }) => {
- if (error) {
- console.error('❌ Error in background task:', error);
- return;
- }
- console.log('📬 Background notification task received!');
- console.log('Data:', JSON.stringify(data, null, 2));
- console.log('Execution Info:', JSON.stringify(executionInfo, null, 2));
- // You can add async logic here if needed (e.g., fetch(), store data)
- }
- );
- Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK);
- Notifications.setNotificationHandler({
- handleNotification: async () => ({
- shouldPlaySound: true,
- shouldSetBadge: true,
- shouldShowBanner: true,
- shouldShowList: true
- })
- });
- export default function RootLayout() {
- useEffect(() => {
- registerForPushNotificationsAsync()
- .then((token) => console.log(`Token: ${token}`))
- .catch((error: any) => console.log(`Error: ${error}`));
- }, []);
- useEffect(() => {
- const responseListener =
- Notifications.addNotificationResponseReceivedListener((response) => {
- console.log('Notification response listener:');
- console.log(JSON.stringify(response, null, 2));
- });
- return () => {
- responseListener.remove();
- };
- }, []);
- useEffect(() => {
- let isMounted = true;
- Notifications.getLastNotificationResponseAsync().then((response) => {
- if (!isMounted || !response?.notification) {
- return;
- }
- console.log('Last notification response:');
- console.log(JSON.stringify(response, null, 2));
- });
- Notifications.clearLastNotificationResponse();
- return () => {
- isMounted = false;
- };
- }, []);
- return (
- <SafeAreaView
- style={{
- flex: 1,
- alignItems: 'center',
- justifyContent: 'center',
- backgroundColor: 'white'
- }}
- >
- <Text>Home Page</Text>
- </SafeAreaView>
- );
- }
- function handleRegistrationError(errorMessage: string) {
- alert(errorMessage);
- throw new Error(errorMessage);
- }
- async function registerForPushNotificationsAsync(): Promise<
- string | undefined
- > {
- if (Platform.OS === 'android') {
- Notifications.setNotificationChannelAsync('default', {
- name: 'default',
- importance: Notifications.AndroidImportance.MAX,
- vibrationPattern: [0, 250, 250, 250],
- lightColor: '#FF231F7C'
- });
- }
- if (Device.isDevice) {
- const { status: existingStatus } =
- await Notifications.getPermissionsAsync();
- let finalStatus = existingStatus;
- if (existingStatus !== 'granted') {
- const { status } = await Notifications.requestPermissionsAsync();
- finalStatus = status;
- }
- if (finalStatus !== 'granted') {
- handleRegistrationError(
- 'Permission not granted to get push token for push notification!'
- );
- return;
- }
- const projectId =
- Constants?.expoConfig?.extra?.eas?.projectId ??
- Constants?.easConfig?.projectId;
- if (!projectId) {
- handleRegistrationError('Project ID not found');
- return;
- }
- try {
- const pushTokenString = (
- await Notifications.getExpoPushTokenAsync({
- projectId
- })
- ).data;
- return pushTokenString;
- } catch (e: unknown) {
- handleRegistrationError(`${e}`);
- }
- } else {
- handleRegistrationError('Must use physical device for push notifications');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment