Been stuck for days on this one. So, I'm using this package for implementing local push notification:
https://github.com/zo0r/react-native-push-notification
I'm able to get local scheduled notification like this:
PushNotification.localNotificationSchedule({
date: new Date(Date.now() + 30 * 1000), // in 30 secs
/* Android Only Properties */
//id: ''+this.lastId, // (optional) Valid unique 32 bit integer specified as string. default: Autogenerated Unique ID
ticker: "My Notification Ticker", // (optional)
autoCancel: true, // (optional) default: true
largeIcon: "ic_launcher", // (optional) default: "ic_launcher"
smallIcon: "ic_notification", // (optional) default: "ic_notification" with fallback for "ic_launcher"
bigText: "My big text that will be shown when notification is expanded", // (optional) default: "message" prop
subText: "This is a subText", // (optional) default: none
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: "view", // (optional) default: view
category: null, // (optional) default: null
userInfo: null, // (optional) default: null (object containing additional notification data)
/* iOS and Android properties */
title: "Scheduled Notification", // (optional)
message: "My Notification Message", // (required)
playSound: true, // (optional) default: true
soundName: "default", // (optional) Sound to play when the notification is shown. Value of 'default' plays the default sound. It can be set to a custom sound such as 'android.resource://com.xyz/raw/my_sound'. It will look for the 'my_sound' audio file in 'res/raw' directory and play it. default: 'default' (default sound is played)
actions: '["Yes", "No"]', // (Android only) See the doc for notification actions to know more
foreground: false, // BOOLEAN: If the notification was received in foreground or not
userInteraction: true, // BOOLEAN: If the notification was opened by the user from the notification area or not
data: { type: "test" } // OBJECT: The push data
});
I want to call a function when user clicks on the notification and when the app opens. To achieve the following I did this in my App.js:
async componentDidMount() {
PushNotification.configure({
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log("NOTIFICATION:", notification);
},
// IOS ONLY (optional): default: all - Permissions to register.
permissions: {
alert: true,
badge: true,
sound: true
},
// Should the initial notification be popped automatically
// default: true
popInitialNotification: true,
/**
* (optional) default: true
* - Specified if permissions (ios) and token (android and ios) will requested or not,
* - if not, you must call PushNotificationsHandler.requestPermissions() later
*/
requestPermissions: true
});
}
But onNotification function doesn't get called.
I've gone through the following questions on SO but no luck.
react-native push notification onNotification doesn't trigger
React Native Push Notification onNotification callback is inconsistent
Android onNotification never called in react-native-push-notification
I've also raised an issue on Github.
What can be the possible solution for this?
for those asking for a solution, I did something like this in my app.js's componentDidMount method:
PushNotification.configure({
// (required) Called when a remote or local notification is opened or received
onNotification: notification => {
console.log(notification);
if (notification.action === "Take") {
//do something here
} else if (notification.action === "Skip") {
//do something here
} else if (notification.action === "Snooze") {
//do something here
}
},
// IOS ONLY (optional): default: all - Permissions to register.
permissions: {
alert: true,
badge: true,
sound: true
},
// Should the initial notification be popped automatically
// default: true
popInitialNotification: true,
/**
* (optional) default: true
* - Specified if permissions (ios) and token (android and ios) will requested or not,
* - if not, you must call PushNotificationsHandler.requestPermissions() later
*/
requestPermissions: true
});
Related
i am able to generate notification along with action buttons but how to call a onpress event based on the button pressed by user? here yes or no
thanks in advance
import PushNotification from 'react-native-push-notification';
function configure() {
PushNotification.configure({
// (required) Called when a remote is received or opened, or local notification is opened
onNotification: function (notification) {
console.log('NOTIFICATION:', notification);
// process the notification
// (required) Called when a remote is received or opened, or local notification is opened
notification.finish();
},
// IOS ONLY (optional): default: all - Permissions to register.
permissions: {
alert: true,
badge: true,
sound: true,
},
// Should the initial notification be popped automatically
// default: true
popInitialNotification: true,
/**
* (optional) default: true
* - Specified if permissions (ios) and token (android and ios) will requested or not,
* - if not, you must call PushNotificationsHandler.requestPermissions() later
* - if you are not using remote notification or do not have Firebase installed, use this:
* requestPermissions: Platform.OS === 'ios'
*/
requestPermissions: true,
requestPermissions: Platform.OS === 'ios',
'content-available': 1,
});
}
function givenotification(title, message) {
PushNotification.localNotification({
channelId: 'channel',
message: message, // (required)
title: title,
message: message, // (required)
actions: ["Yes", "No"]
});
}
I have never used push notification directly,
for my notification i have use React Native Notifee that have this "displayNotification" inside when you try to log Notifee ..
I suggest you to try log "PushNotification" to find a function to display your notification.
You can setup the action as below code:
export const App = () => {
const [permissions, setPermissions] = useState({});
/**
* By calling this function, a notification with category `userAction` will have action buttons
*/
const setNotificationCategories = () => {
PushNotificationIOS.setNotificationCategories([
{
id: 'userAction',
actions: [
{id: 'open', title: 'Open', options: {foreground: true}},
{
id: 'ignore',
title: 'Desruptive',
options: {foreground: true, destructive: true},
},
{
id: 'text',
title: 'Text Input',
options: {foreground: true},
textInput: {buttonTitle: 'Send'},
},
],
},
]);
};
useEffect(() => {
PushNotificationIOS.addEventListener('notification', onRemoteNotification);
});
const onRemoteNotification = (notification) => {
const actionIdentifier = notification.getActionIdentifier();
if (actionIdentifier === 'open') {
// Perform action based on open action
}
if (actionIdentifier === 'text') {
// Text that of user input.
const userText = notification.getUserText();
// Perform action based on textinput action
}
};
};
For more, you can reach out to the official documentation of the library.
https://github.com/zo0r/react-native-push-notification
can someone please let me know where Im going wrong.
From what I can see on instructions....theres no amendments required to Android specific files if you are only using local notifications and also using autolinking....except for adding googlePlayServicesVersion = "<Your play services version>" // default: "+" to android/build.gradle....and <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> plus <uses-permission android:name="android.permission.VIBRATE" /> to AndroidManifest.xml
Below is my main source code
PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: function(token) {
console.log('onRegister token:', token);
},
// (required) Called when a remote is received or opened, or local notification is opened
onNotification: function(notification) {
console.log('onNotification:', notification);
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
// Should the initial notification be popped automatically
popInitialNotification: true,
requestPermissions: true,
});
userNowInactive = () => {
this.showNotification();
}
showNotification = () => {
PushNotification.localNotification({
//ios and android properties
title: 'Face2Face: Beacon Timer Expired',
message: 'Perhaps set your beacon timer for another hour?',
playSound: true,
soundName: 'sound.mp3',
//android only properties
channelId: 'your-channel-id',
autoCancel: true,
// largeIcon: 'ic_launcher',
// smallIcon: 'ic_launcher',
bigText: 'Face2Face: Beacon Timer Expired',
subText: 'Perhaps set your beacon timer for another hour?',
vibrate: true,
vibration: 300,
priority: 'high',
//ios only properties...is there any?
});
};
Did you create a channel?
It seems you need to create one to get it to work.
https://github.com/zo0r/react-native-push-notification#channel-management-android
To use channels, create them at startup and pass the matching channelId through to PushNotification.localNotification or PushNotification.localNotificationSchedule.
PushNotification.createChannel(
{
channelId: "channel-id", // (required)
channelName: "My channel", // (required)
channelDescription: "A channel to categorise your notifications", // (optional) default: undefined.
playSound: false, // (optional) default: true
soundName: "default", // (optional) See `soundName` parameter of `localNotification` function
importance: 4, // (optional) default: 4. Int value of the Android notification importance
vibrate: true, // (optional) default: true. Creates the default vibration patten if true.
},
(created) => console.log(`createChannel returned '${created}'`) // (optional) callback returns whether the channel was created, false means it already existed.
);
I am using "react-native-background-geolocation" for user location tracking when the app is in the background.
Then is it possible to set interval in this function when device powered-up again? (on boot)
I want to get the user location constantly in the background once user turn on device.
How to set "setInterval" on this?
That is my code.
componentWillMount = async () => {
// This handler fires whenever bgGeo receives a location update.
BackgroundGeolocation.onLocation(this.onLocation, this.onError);
// This handler fires when movement states changes (stationary->moving; moving->stationary)
BackgroundGeolocation.onMotionChange(this.onMotionChange);
// This event fires when a change in motion activity is detected
BackgroundGeolocation.onActivityChange(this.onActivityChange);
// This event fires when the user toggles location-services authorization
BackgroundGeolocation.onProviderChange(this.onProviderChange);
////
// 2. Execute #ready method (required)
//
BackgroundGeolocation.ready(
{
// Geolocation Config
desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
distanceFilter: 10,
// Activity Recognition
stopTimeout: 1,
// Application config
debug: true, // <-- enable this hear sounds for background-geolocation life-cycle.
logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
stopOnTerminate: false, // <-- Allow the background-service to continue tracking when user closes the app.
startOnBoot: true, // <-- Auto start tracking when device is powered-up.
// HTTP / SQLite config
url: 'http://yourserver.com/locations',
batchSync: false, // <-- [Default: false] Set true to sync locations to server in a single HTTP request.
autoSync: true, // <-- [Default: true] Set true to sync each location to server as it arrives.
headers: {
// <-- Optional HTTP headers
'X-FOO': 'bar',
},
params: {
// <-- Optional HTTP params
auth_token: 'maybe_your_server_authenticates_via_token_YES?',
},
},
(state) => {
console.log(
'- BackgroundGeolocation is configured and ready: ',
state.enabled,
);
if (!state.enabled) {
////
// 3. Start tracking!
//
BackgroundGeolocation.start(function () {
console.log('- Start success');
});
}
},
);
};
I m coding an application who need push notification in background(app was killed).
its notification app for twitch.
I m store channels with redux persist(asyncstorage).
What should i do? do u have any documentation directly about that ?
You can use a push notification library like https://github.com/zo0r/react-native-push-notification and a background task library like https://github.com/transistorsoft/react-native-background-fetch. Then you can call your push notification(s) inside background tasks.
Keep in mind that the minimum interval between background tasks being run is 15 minutes. So the interval can only be 15 minutes or longer.
To make this answer more useful, here is a previous implementation I've used to handle push notifications in the background to give you an idea of how to go about it:
import PushNotification from 'react-native-push-notification';
export default class NotificationService {
constructor(onRegister, onNotification) {
this.configure(onRegister, onNotification);
this.lastId = 0;
}
// Handles a user push notification registration
configure(onRegister, onNotification, gcm = '') {
PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: onRegister,
// (required) Called when a remote or local notification is opened or received
onNotification: onNotification,
// ANDROID ONLY: GCM Sender ID (optional - not required for local notifications, but is need to receive remote push notifications)
senderID: gcm,
/**
* (optional) default: true
* - Specified if permissions (ios) and token (android and ios) will requested or not,
* - if not, you must call PushNotificationsHandler.requestPermissions() later
*/
requestPermissions: true,
});
}
// Send a direct push notification to the user
localNotif() {
this.lastId++;
PushNotification.localNotification({
/* Android Only Properties */
id: '' + this.lastId,
bigText: 'My big text that will be shown when notification is expanded',
subText: 'This is a subText',
/* iOS and Android properties */
title: 'Local Notification',
message: 'My Notification Message',
actions: '["Yes", "No"]', // (Android only) See the doc for notification actions to know more
});
}
// Schedules a push notification by a given javascript Date object
scheduleNotif(date, title, message) {
this.lastId++;
PushNotification.localNotificationSchedule({
date: date,
/* Android Only Properties */
id: '' + this.lastId,
bigText: '',
subText: '',
/* iOS and Android properties */
title: title,
message: message,
});
}
checkPermission(cbk) {
return PushNotification.checkPermissions(cbk);
}
cancelNotif() {
PushNotification.cancelLocalNotifications({ id: '' + this.lastId });
}
cancelAll() {
PushNotification.cancelAllLocalNotifications();
}
}
// ...
import BackgroundFetch from 'react-native-background-fetch';
const initBackGroundFetch = () => {
BackgroundFetch.configure(
{
minimumFetchInterval: 15, // <-- minutes (15 is minimum allowed)
// Android options
forceAlarmManager: false, // <-- Set true to bypass JobScheduler.
stopOnTerminate: false,
startOnBoot: true,
requiredNetworkType: BackgroundFetch.NETWORK_TYPE_ANY, // Network connection needed
},
async taskId => {
// Do stuff with notifications, for example:
const notificationService = new NotificationService(
() => {//... what to do on register},
() => {//... what to do on notification }
)
const date = new Date(Date.now() + 60 * 1000) // adjust according to your use case
notificationService.scheduleNotif(date, "title", "message");
BackgroundFetch.finish(taskId);
},
error => {
console.log('[js] RNBackgroundFetch failed to start');
},
);
};
const App = () => {
useEffect(() => {
initBackGroundFetch();
}, []);
return (
// ...
);
};
The NotificationService is an adjusted version of an example the react native push notification library provides found here: https://github.com/zo0r/react-native-push-notification/blob/master/example/NotifService.js.
I am trying to send a mobile push notification to my android device based on apex trigger, and I didn't see notification banner but in console I can see onNotification event fired and I can see my payload info.
I have followed In react native app react-native-push-notification library, all changes are done as per the document mention here https://www.npmjs.com/package/react-native-push-notification.
updated MobilePushServiceDevice whenever user open the with token and service type
On FCM created the project and follow this document https://firebase.google.com/docs/cloud-messaging/android/client
Salesforce create connected enable push notification added server key
here is react code
const notification = PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: function (token) {
//Send this token to salesforce
let createPayload = {
ServiceType: getSystemName() == 'Android' ? 'androidGcm' : 'apple',
ConnectionToken: token.token
};
// register device with salesforce
},
// (required) Called when a remote is received or opened, or local notification is opened
onNotification: function (notification) {
console.log("NOTIFICATION:", notification);
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
// (optional) Called when Registered Action is pressed and invokeApp is false, if true onNotification will be called (Android)
onAction: function (notification) {
console.log("ACTION:", notification.action);
console.log("NOTIFICATION:", notification);
// process the action
},
// (optional) Called when the user fails to register for remote notifications. Typically occurs when APNS is having issues, or the device is a simulator. (iOS)
onRegistrationError: function (err) {
console.error(err.message, err);
},
// IOS ONLY (optional): default: all - Permissions to register.
permissions: {
alert: true,
badge: true,
sound: true,
},
visibility: 'public',
// Should the initial notification be popped automatically
// default: true
popInitialNotification: true,
senderID: "1019984307481",
requestPermissions: true,
});
here is my apex code
`Messaging.PushNotification msg = new Messaging.PushNotification();
Map<String, Object> androidPayload = new Map<String, Object>();
Set<String> userSet = new Set<String>();
androidPayload.put('title', idVSnickname.get(cbuId)+' assigned you a task');
androidPayload.put('message', subject);
androidPayload.put('parentId', str[4].trim());
androidPayload.put('id', str[0].trim());
userSet.add(accIdVSuserId.get(accId));
msg.setPayload(androidPayload);
msg.send('Mimit', userSet);`