Is there a way to disable the vibration via push notification payload when notification displayed?
This is my sample payload.
$payload = array
(
'title' => 'Title',
'message' => 'Message',
'vibrate' => 0,
'content-available' => 1
);
But vibration is still working even I set the vibrate value to 0.
Any help will be greatly appreciated. Thank you!
Within the PushNotification.init() method you also need to set 'vibrate' to false, as it defaults to true for Android. iOS however does not have a similar setting, but setting sound to false may also work (i haven't tested this).
var push = PushNotification.init({
android: {
senderID: "12345679",
vibrate: false
},
ios: {
sound: false
},
windows: {}
});
https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/API.md#pushnotificationinitoptions
Related
I'm currently using this library in react-native to schedule local notification, when i tap of notification either from notification centre or from top of the app, i want to redirect the user to specific screen. Currently react-native-push-notification lib using old UILocalNotification classes which are already deprecated.
Below is my code to configure local notification.
onNotification is a callback method triggers when user launches the app from notification centre for iOS and similarly onAction is for Android.
/**
* To configure for local notifications
*/
export function localNotificationConfigure() {
PushNotification.configure({
onNotification: async function (notification) {
console.log('notification.data', notification.userInteraction);
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
onAction: async function (notification) {
console.log('notification', notification.userInteraction);
},
permissions: {
alert: true,
badge: true,
sound: true,
},
popInitialNotification: true,
requestPermissions: Platform.OS === 'ios',
});
}
Is there any way that i can achieve this. Is it because of lib using UILocalNotification which is deprecated and i'm not able to get the action back in the code. Any help is appreciated.
This link helped me in achieving my desired functionality.
On Android, I want to be able to show a persistent notification with two buttons even when the app is in the background or when the phone is locked. Basically, like a WhatsApp incoming call notification.
I know how to do it in Java but I don't know how to do it in Flutter. I've read similar questions on SO but none have provided a good answer.
FYI, I know how to send and receive FCM notifications. I know how to display a normal notification when a FCM message is sent while the app is in the background.
After wasting an entire week, here is the solution I found.
Keep your app running in the background and make sure it is not closed by the user. This tutorial explains how to do it: https://github.com/ppicas/flutter-android-background
If the solution above is too complicated, use the flutter_background to do more or less the same thing (the first solution is better because it also prevents the user from closing the app).
Make sure the flutter activity can be displayed over the lock screen by adding this to your activity's declaration in your manifest:
android:showWhenLocked="true"
Last thing is to use a wakelock in flutter when your app receives a notification, and you want to display a full screen "call received" widget.
You can use firebase_messaging and awesome_notifications
add this in your firebase background subscription handler
await AwesomeNotifications().createNotification(
content: NotificationContent(
id: createuniqueId(),
channelKey: 'basic_channel',
title: message.data['title'],
body: message.data['body'],
wakeUpScreen: true,
fullScreenIntent: true,
autoDismissible: false,
category: NotificationCategory.Call,
locked: true,
displayOnForeground: true,
),
actionButtons: [
NotificationActionButton(
key: 'accept',
label: 'Accept',
),
NotificationActionButton(
isDangerousOption: true,
key: 'reject',
label: 'Reject',
),
],
);
add this is your main()
AwesomeNotifications().initialize(
'resource://drawable/ic_icon',
[
NotificationChannel(
channelKey: 'basic_channel',
channelName: 'Basic Notification',
channelDescription: 'Hello world',
importance: NotificationImportance.High,
channelShowBadge: true,
vibrationPattern: highVibrationPattern
),
]
);
I have been working on adding custom sounds to push notifications for a react-native app using firebase-admin version ^9.2.0 and react-native-push-notification version ^5.1.0.
The reason why I haven't upgraded to the latest version of react-native-push-notification is because custom sounds do not seem to work even with proper channel configuration. We are also using expo, which appears to be causing a startup error when using version 7+.
I have two mp3 files called regular.mp3 and mass.mp3. The firebase functions that send the push notifications send the message using the common data object, but also platform-specific fields for push notification sounds:
admin.messaging().send({
data: {
title,
body,
lat: data.Latitude.toString(),
lng: data.Longitude.toString(),
notificationType: data.NotificationType.toString(),
},
notification:{title,body},
apns:{
payload:{
aps:{
alert:{
title,
body,
},
sound: data.NotificationType === 1 ? "mass.mp3" : "regular.mp3",
},
},
},
android: {
priority: "high",
data: {
sound: data.NotificationType === 1 ? "mass" : "regular",
},
notification: {
sound: data.NotificationType === 1 ? "mass" : "regular",
},
},
topic: topic,
})
From my understanding, the data field under android does contain the payload that will be added to the root-level data object when the app is killed and receive the notification. The plugin's source also seems to be using that exact data field to set the notification sound (in RNReceivedMessageHandler.java):
JSONObject data = getPushData(notificationData.get("data"));
if (data != null) {
if (!bundle.containsKey("message")) {
bundle.putString("message", data.optString("alert", null));
}
if (!bundle.containsKey("title")) {
bundle.putString("title", data.optString("title", null));
}
if (!bundle.containsKey("sound")) {
bundle.putString("soundName", data.optString("sound", null));
}
if (!bundle.containsKey("color")) {
bundle.putString("color", data.optString("color", null));
}
Here is what I got so far:
custom sounds work great when the app is in foreground
custom sounds work great when app is in background
default sound plays when app is killed
Here is the code currently in place to manage the notifications:
In index.ts:
PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: function(token) {
console.log("TOKEN:", token);
},
// (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(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,
},
popInitialNotification: true,
requestPermissions: true,
});
In App.js
CreateIncidentPushNotification=(remoteMessage)=>{
const {data} = remoteMessage;
PushNotification.localNotification({
title: data.title,
message: data.body,
playSound: true,
soundName: data.notificationType === "1" ? "mass" : "regular",
});
}
I was wondering if anyone else had an idea about what could be going on. The notification still manages to get to my device even when the app is killed, which is great. The only missing part is the sound.
Okay so I finally got it working. I had to add the following to my manifest file and comment a receiver:
<meta-data android:name="com.dieam.reactnativepushnotification.notification_channel_name"
android:value="my-channel"/>
<meta-data android:name="com.dieam.reactnativepushnotification.notification_channel_description"
android:value="my channel"/>
<!-- Change the value to true to enable pop-up for in foreground (remote-only, for local use ignoreInForeground) -->
<meta-data android:name="com.dieam.reactnativepushnotification.notification_foreground"
android:value="false"/>
<!-- Change the value to false if you don't want the creation of the default channel -->
<meta-data android:name="com.dieam.reactnativepushnotification.channel_create_default"
android:value="true "/>
<!-- Change the resource name to your App's accent color - or any other color you want -->
<meta-data android:name="com.dieam.reactnativepushnotification.notification_color"
android:resource="#color/white"/> <!-- or #android:color/{name} to use a standard color -->
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationActions" />
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
<!-- <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver> -->
Then, I had to use channels in order to get the sounds working in foreground, background, and when the app is killed. As you can see, I created a custom channel in my manifest file and activated the default channel as well. I HAD to activate the default channels because I have two notification types that require different sounds. Using a single channel was NOT WORKING.
Once the manifest file has been updated, I modified the firebase functions (using firebase-admin to do the following:
admin.messaging().send({
data: {
title,
body,
lat: data.Latitude.toString(),
lng: data.Longitude.toString(),
notificationType: data.NotificationType.toString(),
},
notification:{title,body},
apns:{
payload:{
aps:{
alert:{
title,
body,
},
sound: data.NotificationType === 1 ? "mass.mp3" : "regular.mp3",
},
},
},
android: {
priority: "high",
data: {
sound: data.NotificationType === 1 ? "mass" : "regular",
channelId: data.NotificationType === 1 ? "my-channel" : "fcm_fallback_notification_channel",
},
notification: {
sound: data.NotificationType === 1 ? "mass" : "regular",
channelId: data.NotificationType === 1 ? "my-channel" : "fcm_fallback_notification_channel",
},
},
topic: topic,
})
.then((response) => {
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
Firebase was now aware of the two channels I was using. I then moved to the application code and handled the local notification like this:
PushNotification.localNotification({
title: data.title,
message: data.body,
playSound: true,
soundName: data.notificationType === "1" ? "mass" : "regular",
channelId: data.notificationType === "1" ? "my-channel" : "fcm_fallback_notification_channel"
});
I also activated both onMessage and setBackgroundMessageHandler handlers of the react-native-push-notification package:
messaging().onMessage(this.sendMessage);
messaging().setBackgroundMessageHandler(this.sendMessage);
Where this.sendMessage is responsible to call the localNotification call mentioned above.
By the way, I am stil getting duplicated notifications when the app is in background, so this is purely a fix for the sounds.
UPDATE:
removing the setBackgroundMessageHandler removed the duplicates!!!! :)
Peace!
I'm writing an app that sends a local push notification every fifteen minutes while a background timer is running via react-native-push-notification. If notification n isn't acted on by the user, when notification n+1 is pushed, I'd like to delete notification n.
The things I've tried so far are to set popInitialNotification to true when running PushNotification.configure() and setting ongoing to true when calling PushNotification.localNotification(). I've also tried adding an id when calling localNotification() and then calling PushNotification.cancelLocalNotifications({id: myId}), but the documentation explicitly says that cancelLocalNotifications() only cancels scheduled notifications (and I'm pretty sure it means only future ones).
componentWillMount() {
PushNotification.configure({
permissions: {
alert: true,
badge: true,
sound: true
},
popInitialNotification: true,
});
}
doPushNotification() {
if (AppState.currentState !== 'active') {
PushNotification.localNotification({
vibration: 500,
message: 'my message',
ongoing: true,
});
}
}
Currently I'm only working on the Android version, but soon I'll work on the iOS version, so a general solution (or the solution for each) would be most helpful.
I'm not totally sold on react-native-push-notification, either, if there's a better React Native library out there; I just haven't found one.
Edit
I figured it out for Android. Setting the id when calling PushNotification.localNotification() to the same value as the previous notification will overwrite the notification.
I'm still installing XCode on my Mac, so I can't test the current behavior on iOS just yet. However, the react-native-push-notification readme says that id is an Android-only option (as is ongoing). I may still need help getting the iOS notifications to do what I want.
The docs for react-native-push-notification state that you can cancel a ios local notification using userInfo like this:
PushNotification.localNotification({
...
userInfo: { id: '123' }
...
});
PushNotification.cancelLocalNotifications({id: '123'});
I have tested this, and it works.
For android, this somehow worked:
Creating the notification :
PushNotification.localNotificationSchedule({
message: message ,
date: new Date(date),
repeatType: "minute",
id: JSON.stringify(id),
userInfo: { id: JSON.stringify(id) }
});
PushNotification.cancelLocalNotifications({ id: id});
Having the id stringified worked with cancelling the android push notification.
you can add this code inside handleAppStateChange(appState)
if (appState === 'active') {
PushNotification.cancelAllLocalNotifications()
}
if you are useing react-native-push-notification lib.
then you can use this code in componentDidMount section
PushNotification.getDeliveredNotifications((all) => {
console.log(all, "notification liast");
PushNotification.removeAllDeliveredNotifications();
});
here you can get all notification list and clear all list after open your app.
these code work for me in ANDROID device (i did not test it in IOS device)
Below code works on both iOS and Android :
We need to stringify id so that it works in android and the date must be created from Date class not from some library like moment.
const LocalNotificationSchedule = (id, afterSec, message) => {
PushNotification.localNotificationSchedule({
id: id+'',
message: message,
date: new Date(Date.now() + afterSec * 1000),
playSound: true,
soundName: 'default',
vibrate: true,
vibration: 300,
playSound: true,
soundName: 'default',
ignoreInForeground: false
})
}
const CancelLocalNotifications = (id) => {
PushNotification.cancelLocalNotifications({id: id+''})
}
Try to delete the notification with cancelLocalNotifications.
I'm using this library.
I'm attempting to get push notifications to display in the notifications tray on my Nexus 5 (android 6.0.1). Using React Native 0.42, React Native CLI 2.0.1. I'm developing on Ubuntu 14.04.
I'm using firebase. I go into my console > notifications > send a message > specific device (which I get from remote debugging console.log, below).
I am logging notifications, as you can see in code, and they do get to my device, as I can see them in the logs.
But, I don't know how to display them in the notifications tray. Looking through the docs and searching forums, it seems they should show up by default.
componentDidMount() {
FCM.requestPermissions(); // for iOS
FCM.getFCMToken().then(token => {
console.log(token)
// store fcm token in your server
});
this.notificationListener = FCM.on(FCMEvent.Notification, async (notif) => {
console.log(notif)
});
});
It seems that "custom_notification" is required to display the notification in the top tray. I added this to my payload:
"custom_notification": {
"body": "test body",
"title": "test title",
"color":"#00ACD4",
"priority":"high",
"icon":"ic_notif",
"group": "GROUP",
"id": "id",
"show_in_foreground": true
}
So, I think the app must receive the notification, parse out the data, and add this custom_notification parameter.
How about the following in your constructor:
FCM.requestPermissions(); // for iOS
FCM.getFCMToken().then(token => {
console.log(token)
// store fcm token in your server
});
this.notificationListener = FCM.on(FCMEvent.Notification, async (notif) => {
// do some component related stuff
console.log(notif);
//alert(notif.fcm.body);
FCM.presentLocalNotification({
id: "UNIQ_ID_STRING", // (optional for instant notification)
title: "My Notification Title", // as FCM payload
body: notif.fcm.body, // as FCM payload (required)
sound: "default", // as FCM payload
priority: "high", // as FCM payload
click_action: "ACTION", // as FCM payload
badge: 10, // as FCM payload IOS only, set 0 to clear badges
number: 10, // Android only
ticker: "My Notification Ticker", // Android only
auto_cancel: true, // Android only (default true)
large_icon: "ic_launcher", // Android only
icon: "ic_launcher", // as FCM payload, you can relace this with custom icon you put in mipmap
big_text: "Show when notification is expanded", // Android only
sub_text: "This is a subText", // Android only
color: "red", // Android only
vibrate: 300, // Android only default: 300, no vibration if you pass null
tag: 'some_tag', // Android only
group: "group", // Android only
picture: "https://google.png", // Android only bigPicture style
ongoing: true, // Android only
my_custom_data: 'my_custom_field_value', // extra data you want to throw
lights: true, // Android only, LED blinking (default false)
show_in_foreground: true // notification when app is in foreground (local & remote)
});
});
FCM.subscribeToTopic('test_topic');