import AsyncStorage from '@react-native-async-storage/async-storage';
import messaging from '@react-native-firebase/messaging';
export async function requestUserPermission() {
const authStatus = await messaging().requestPermission();
const isApproved =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (isApproved) {
// console.log('Authorization status: ', authStatus);
getFCMToken();
} else {
console.log('Authorization status failed');
showError('Authorization status: Failed');
}
}
import AsyncStorage from '@react-native-async-storage/async-storage';
import messaging from '@react-native-firebase/messaging';
import {showError} from '../util/helper';
import {Linking} from 'react-native';
import {base_url} from './../util/linking';
const getFCMToken = async () => {
let fcmToken = await AsyncStorage.getItem('fcmToken');
console.log('Old saved FCM Token------->', fcmToken);
if (!fcmToken) {
try {
const new_fcmToken = await messaging().getToken();
if (new_fcmToken) {
console.log('New generated FCM Token====>', new_fcmToken);
await AsyncStorage.setItem('fcmToken', new_fcmToken);
}
} catch (error) {
// console.log('FCM Token not generated*********', error);
showError(error.message);
}
}
};
export const notificationListener = () => {
messaging().onNotificationOpenedApp(msg => {
console.log('onOpened in background state', msg);
Linking.openURL(base_url + msg.data.screen);
});
messaging().onMessage(async msg => {
console.log('Received in forground on Message===========>', msg);
});
messaging()
.getInitialNotification()
.then(msg => {
if (msg) {
console.log('Initial inactive state', msg.notification);
}
});
};
export const unsubscribeFCMNotification = () => {
const unsubscribe = messaging().onMessage(async remoteMessage => {
Alert.alert('A new FCM message arrived !', JSON.stringify(remoteMessage));
});
return unsubscribe;
};
import React, {useEffect} from 'react';
import {Button, StyleSheet, View} from 'react-native';
import {notificationListener, requestUserPermission} from '../fcm-services';
export const ScreenA = () => {
useEffect(() => {
requestUserPermission();
notificationListener();
// unsubscribeFCMNotification();
}, []);
return (
<View style={styles.container}>
<RemoteNotification />
<Button title={'Click Here'} onPress={() => console.log('Button clicked')} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'white',
},
});
import {useEffect} from 'react';
import {PermissionsAndroid, Platform} from 'react-native';
import PushNotification from 'react-native-push-notification';
const checkApplicationPermission = async () => {
if (Platform.OS === 'android') {
try {
await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
);
} catch (error) {
console.error(error);
}
}
};
const RemoteNotification = () => {
useEffect(() => {
checkApplicationPermission();
PushNotification.getChannels(function (channel_ids) {
channel_ids.forEach(id => {
PushNotification.deleteChannel(id);
});
});
PushNotification.configure({
onRegister: function (token) {
console.log('Token Generated=====>', token);
},
onNotification: function (notification) {
const {message, title, name, id} = notification;
let strTitle: string = JSON.stringify(title).split('"').join('');
let strBody: string = JSON.stringify(message).split('"').join('');
let strName: string = JSON.stringify(name).split('"').join('');
const key: string = JSON.stringify(id).split('"').join('');
PushNotification.createChannel(
{
channelId: key,
channelName: 'Remote Message',
channelDescription: 'Notification for remote',
importance: 4,
vibrate: true,
},
created => console.log(`Remoted Channel cretaed=======> ${created}`),
);
PushNotification.localNotification({
channelId: key,
title: strTitle,
message: strBody,
name: strName,
});
console.log(
'REMOTE NOTIFICATION===>',
title,
message,
name,
id,
notification,
);
},
senderID: 'xxxxxxxxxx',
popInitialNotification: true,
requestPermissions: true,
});
}, []);
return null;
};
export default RemoteNotification;
import PushNotification from 'react-native-push-notification';
const LocalNotification = () => {
const key = Date.now().toString();
PushNotification.createChannel(
{
channelId: key,
channelName: 'Local message',
channelDescription: 'Notification for local message',
importance: 4,
vibrate: true,
},
created => console.log(`createdChannel returned ${created}`),
);
PushNotification.localNotification({
channelId: key,
title: 'Local Message',
message: 'Saten Push Message',
});
};
export default LocalNotification;
Use created notification component
import React, {useEffect} from 'react';
import {Button, StyleSheet, View} from 'react-native';
import {notificationListener, requestUserPermission} from '../fcm-services';
export const ScreenA = () => {
useEffect(() => {
requestUserPermission();
notificationListener();
// unsubscribeFCMNotification();
}, []);
return (
<View style={styles.container}>
<RemoteNotification />
<Button title={'Click Here'} onPress={() => console.log('Button clicked')} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'white',
},
});