Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'react-native-push-notification' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
function init() {
const intl = constructIntl();
globalHandler = new Handler(null, intl);
let lastTokenRegistration = null;
PushNotification.configure({
onRegister: async function (tokenRegistration: TokenRegistration) {
// Don't re-process if we've already already recorded this token
if (lastTokenRegistration == tokenRegistration.token) {
return;
}
lastTokenRegistration = tokenRegistration.token;
setupMixpanelToken(tokenRegistration);
await saveToken(tokenRegistration);
},
onNotification: globalHandler.receivedNotification,
// ANDROID ONLY: GCM Sender ID (optional - not required for local notifications, but is need to receive remote push notifications)
senderID: '911140565156',
// IOS ONLY (optional): default: all - Permissions to register.
configure: (dispatch) => {
// https://github.com/zo0r/react-native-push-notification
PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: (token) => {
if (__DEV__) console.log('TOKEN:', token)
},
// (required) Called when a remote or local notification is opened or received
onNotification: (notification) => {
dispatch(NotificationActions.addNotification(notification.message))
},
// ANDROID ONLY: (optional) GCM Sender ID.
senderID: 'YOUR GCM SENDER ID',
// IOS ONLY (optional): default: all - Permissions to register.
permissions: {
(function() {
// Register all the valid actions for notifications here and add the action handler for each action
PushNotification.registerNotificationActions([ i18n.t('notificationAction') ])
DeviceEventEmitter.addListener('notificationActionReceived', (action) => {
console.log ('Notification action received: ' + action)
const info = JSON.parse(action.dataJSON)
if (info.action == i18n.t('notificationAction')) {
if (Platform.OS === 'android') BackHandler.exitApp()
else RNExitApp.exitApp()
}
})
})()
const configure = PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: (token) => {
console.log( 'TOKEN:', token )
},
// (required) Called when a remote or local notification is opened or received
onNotification: (notification) => {
console.log( 'NOTIFICATION:', notification )
// process the notification
// required on iOS only (see fetchCompletionHandler docs: https://facebook.github.io/react-native/docs/pushnotificationios.html)
notification.finish(PushNotificationIOS.FetchResult.NoData)
},
// ANDROID ONLY: GCM Sender ID (optional - not required for local notifications, but is need to receive remote push notifications)
senderID: "YOUR GCM SENDER ID",
// IOS ONLY (optional): default: all - Permissions to register.
permissions: {
alert: true,
async componentDidMount() {
// Add an event listener to log registration errors in development
if (__DEV__) {
PushNotificationIOS.addEventListener('registrationError', error =>
console.warn(error)
)
}
PushNotification.configure({
// Called when Token is generated (iOS and Android) (optional)
onRegister: deviceToken => {
// Save the device token into redux for later use with other accounts
this.props.setDeviceToken(deviceToken['token'])
},
// Called when a remote or local notification is opened or received
onNotification: notification => {
this.onNotification(notification)
// https://facebook.github.io/react-native/docs/pushnotificationios.html
if (Platform.OS === 'ios') {
notification.finish(PushNotificationIOS.FetchResult.NoData)
}
},
// Android only
senderID: '162663374736',
// iOS only
onNotification: function(notification) {
console.log(notification.notification.icon)
PushNotification.localNotification({
largeIcon: notification.notification.icon, // (optional) default: "ic_launcher"
smallIcon: notification.notification.icon, // (optional) default: "ic_notification" with fallback for "ic_launcher"
bigText: notification.notification.body, // (optional) default: "message" prop
color: "blue", // (optional) default: system default
vibrate: true, // (optional) default: true
vibration: 300, // vibration length in milliseconds, ignored if vibrate=false, default: 1000
tag: 'some_tag', // (optional) add tag to message
group: "group", // (optional) add group to message
ongoing: false, // (optional) set whether this is an "ongoing" notification
/* iOS only properties
alertAction: // (optional) default: view
category: // (optional) default: null
userInfo: // (optional) default: null (object containing additional notification data)
*/
if (PushService._token.os === 'android') {
data.token = {
gcm: PushService._token.token,
};
} else if (PushService._token.os === 'ios') {
data.token = {
apn: PushService._token.token,
};
}
// console.log('==============> push =================', data);
Meteor.call('raix:push-update', data, (err, res) => {
AppUtil.debug('Push backend', JSON.stringify(res));
});
// clear badges on init
PushNotification.setApplicationIconBadgeNumber(0);
}
}
incomingVC(groupID, rUID, rUName) {
console.log('Kumar push VCUTIL invc ', groupID, rUID, rUName);
this._gid = groupID;
this._remoteuid = rUID;
this._remoteName = rUName;
PushNotification.cancelAllLocalNotifications();
PushNotification.localNotificationSchedule({
message: `Video Calling ${this._remoteName}`, // (required)
playSound: false,
autoCancel: false,
vcData: {
groupID,
rUID,
},
date: new Date(Date.now()), // in 60 secs
// actions: '["Accept", "Reject"]',
});
// InCallManager.startRingtone('_BUNDLE_');
// InCallManager.turnScreenOn();
// if (!this._net) {
// this._net = new Network();
const currUser = this.service.loggedInUserObj;
for (let i = 0; i < msgs.length; i += 1) {
const inM = msgs[i];
console.log('Ezhil chatservice message ', inM);
let msgText = inM.msg;
if (inM.t && inM.t === 'mgcall_init') {
msgText = 'Started a Call!';
if (!(inM.u._id === currUser._id) && (group.findMessageById(inM._id) === null)) {
if (group && group.type === 'direct') {
msgText = 'Started a Call!';
this.incomingVC(currUser, inM.ts, inM.rid, group);
} else {
const msgTs = moment(inM.ts);
const currentTsDiff = moment().diff(msgTs, 'minutes');
if (currentTsDiff < 1) {
PushNotification.localNotificationSchedule({
message: `Video Call started in ${group.name}`, // (required)
playSound: true,
soundName: 'vcring.mp3',
date: new Date(Date.now()), // in 60 secs
});
}
}
}
}
const m = this.yap2message(inM._id, inM.rid, msgText, inM.ts, inM.u._id, inM.u.username, inM.u.name);
m.original = inM;
if (inM.attachments && inM.attachments.length > 0) {
const atM = inM.attachments[0];
if (m.text === '') {
if (atM.description) {
m.text = atM.description;
incomingVC(groupID, rUID, rUName) {
console.log('Kumar push VCUTIL invc ', groupID, rUID, rUName);
this._gid = groupID;
this._remoteuid = rUID;
this._remoteName = rUName;
PushNotification.cancelAllLocalNotifications();
PushNotification.localNotificationSchedule({
message: `Video Calling ${this._remoteName}`, // (required)
playSound: false,
autoCancel: false,
vcData: {
groupID,
rUID,
},
date: new Date(Date.now()), // in 60 secs
// actions: '["Accept", "Reject"]',
});
// InCallManager.startRingtone('_BUNDLE_');
// InCallManager.turnScreenOn();
// if (!this._net) {
// this._net = new Network();
// }
const result = await context.fetchLoginMessages()
const date = new Date(Date.now() + 1000)
// for each key
for (const key in result) {
// skip loop if the property is from prototype
if (!result.hasOwnProperty(key)) continue
const obj = result[key]
if (obj.otpResetPending) {
if (Platform.OS === Constants.IOS) {
PushNotification.localNotificationSchedule({
title: s.strings.otp_notif_title,
message: sprintf(s.strings.otp_notif_body, key),
date
})
} else {
PushNotification.localNotificationSchedule({
message: s.strings.otp_notif_title,
subText: sprintf(s.strings.otp_notif_body, key),
date
})
}
}
}
} catch (error) {
console.error(error)
}
})
await AsyncStorage.setItem(Constants.LOCAL_STORAGE_BACKGROUND_PUSH_KEY, now.toString())