I'm trying twilio services and sending notification works fine but I can't set up the sms fallback properly as this is not really documented.
HashMap<String, Object> smsNumbers = new HashMap<>();
smsNumbers.put("?", "?");
LOGGER.debug("Adding SMS fallback to: {}", smsNumbers);
LOGGER.debug("Calling sendNotification to {}", identity);
Notification notification = Notification
.creator(twilioServiceSid)
.setBody(message)
.setData(data)
.setIdentity(identity)
.setSms(smsNumbers)
.create(restClient);
I'm getting the following error :
com.twilio.exception.ApiException: Parameter 'Sms' contains unrecognized property.
at com.twilio.rest.notify.v1.service.NotificationCreator.create(NotificationCreator.java:316) [twilio-7.15.1.jar:]
How to fill the HashMap ?
Twilio developer evangelist here.
When setting data that will be sent over SMS channels from a notification, you can set any of the following keys to override the general notification: body, media_urls, status_callback, and max_price.
So, if you wanted to send an alternative body over SMS, you would use the following code:
HashMap<String, Object> smsNumbers = new HashMap<>();
smsNumbers.put("body", "This is just for the SMS notifications");
LOGGER.debug("Adding SMS fallback to: {}", smsNumbers);
LOGGER.debug("Calling sendNotification to {}", identity);
Notification notification = Notification
.creator(twilioServiceSid)
.setBody(message)
.setData(data)
.setIdentity(identity)
.setSms(smsNumbers)
.create(restClient);
Let me know if that helps.
Related
I'm trying to listen to a Google Calendar event I created using a watch request but I have no clue how to get the event details once I get the push notification.
So this is what I have so far, I create the Calendar event using JavaScript (it prompts the user for authorization):
function createEvent(data) {
var request = gapi.client.calendar.events.insert({
'calendarId': 'primary',
'resource': data
});
request.execute(function(event) {
if (!event.code) {
openToast('The event was added to your Google Calendar')
watchEvent(data.id);
}
});
}
And then I create a watch request to get the PUSH notifications:
function watchEvent(eventId) {
gapi.client.calendar.events.watch({
auth: gapi.auth2.getAuthInstance(),
resource: {
id: eventId,
type: 'web_hook',
address: webhookUrl
},
calendarId: 'primary'
}).execute(function onWatchCalendarEvent(event) {
if (event.error) {
console.error('Error creating event watch webhook', event.error);
}
});
}
So far so good, this is working OK and I receive a PUSH notification with the channelID from which I can get my own internal meetingId.
#PostMapping
public void onCalendarEventUpdate(#RequestHeader(name = "x-goog-channel-id") String channelId,
#RequestHeader(name = "x-goog-resource-state") String resourceState) {
log.info("Received Google Calendar event update notification: " + resourceState);
// only when the event is modified google posts the resource state as "exists"
// (what kind of name is that anyway?)
if (resourceState.equals("exists")) {
// get the meeting ID from the channel ID
Long meetingId = findMeetingIdFromChannelId(channelId);
calendarService.updateMeeting(meetingsService.findById(meetingId));
}
}
I've read the docs for Authorizing Requests, PUSH Notifications and Java API Getting Started but they all prompt for the user authorization. Since this PUSH notification is happening asynchronously how am I supposed to get the updated event details? Thanks
if you have the calendar and event id (e.g. from the notification you get from Google that you receive and parse at your webhookUrl location), you can make calendar api calls to get all the event details: https://developers.google.com/calendar/api/v3/reference/events/get
Unable to send firebase fcm push notiication to android device.
When I send test message from firebase console, it goes to device. So Android side code is working fine.
For Backend Java server, I am using firebase sdk
public void sendNotification2(String notification, String title, String to) {
String registrationToken = to;
Message message = Message.builder().putData("score", "850").putData("time", "2:45")
.setToken(registrationToken).build();
String response;
response = FirebaseMessaging.getInstance().send(message);
System.out.println("Successfully sent message: " + response);
}
Code outputs: Successfully sent message: projects/myappname/messages/0:1590590793114288%9cceaf10deffd7abc
But the device doesn't receive notification.
It would be important to clarify if your app is in background or foreground while sending the message from backend, in fcm this is important to consider.
In this case, you send a data message, not a notification message.
The difference is explained in the doc:
https://firebase.google.com/docs/cloud-messaging/android/receive
That means, you should receive this message in the overriden onMessageReceived(...)-method when the app is in the foreground and in the background.
(You can control this with a debug log command.)
If you use data messages, you can define custom key-value pairs and implement the notification process on your own, when the app is in the foreground and background. With firebase console in contrast, you send notification messages, they are processed in the background of your app automaticly, in the foreground the overriden onMessageReceived(...) is triggered.
Here is an example of building a notification message (with different priorities which should not confuse you):
private Message createFCMMessageWithNormalPriority(String notificationMessage) {
return Message.builder().setNotification(createFCMNotification(notificationMessage)).setToken(registrationToken)
.setAndroidConfig(createAndroidConfigWithNormalMessagePriority()).build();
}
private Message createFCMMessageWithHighPriority(String notificationMessage) {
return Message.builder().setNotification(createFCMNotification(notificationMessage)).setToken(registrationToken)
.setAndroidConfig(createAndroidConfigWithHighMessagePriority()).build();
}
private AndroidConfig createAndroidConfigWithHighMessagePriority() {
return createAndroidConfigWithPriority(Priority.HIGH);
}
private AndroidConfig createAndroidConfigWithNormalMessagePriority() {
return createAndroidConfigWithPriority(Priority.NORMAL);
}
private AndroidConfig createAndroidConfigWithPriority(Priority priority) {
return AndroidConfig.builder().setPriority(priority).build();
}
private Notification createFCMNotification(String notificationMessage) {
return Notification.builder().setBody(notificationMessage).setTitle(NOTIFICATION_CONTENT_TITLE).build();
}
I want to customize notification layout when app closed and notification arrives a default notification is shown where I want a custom notification to be displayed even if app the closed.
The following is my code for Firebase onMessageReceievd
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d("remoteMessage",String.valueOf(remoteMessage.getFrom()));
if (remoteMessage.getData().size() > 0) {
Log.e("MyFirebaseMsgService", "Data Payload: " + remoteMessage.getData().toString());
try {
JSONObject json = new JSONObject(remoteMessage.getData().toString());
sendPushNotificationData(json);
} catch (Exception e) {
Log.e("MyFirebaseMsgService", "Exception: " + e.getMessage());
}
}
if (remoteMessage.getNotification() != null) {
//Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
sendPushNotification(String.valueOf(remoteMessage.getNotification().getBody()),String.valueOf(remoteMessage.getNotification().getTitle()));
}
}
I used BitTextStyle() to add highlighted text in notification.
return new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_mono)
.setContentTitle(title)
.setContentText(message)
.setLargeIcon(icon)
.setColor(ContextCompat.getColor(context, R.color.notification_color))
.setStyle(new NotificationCompat.BigTextStyle().bigText(title))
.setStyle(new NotificationCompat.BigTextStyle().bigText(message).setSummaryText("#hashtag"))
.setShowWhen(true)
.setAutoCancel(true);
Firebase Remote message has notification and data fields. According to this documentation Firebase handles remoteMessage.notification automatically and pass remoteMessage.data into intent extras when your app is closed. But when your app is active remoteMessage comes to your receiver and handled by it. But there are few scenarios which depends on remoteMessage state. See the table in documentation. So, if you want to handle all notification even when your app is closed, you need to put all your data into remoteMessage.data field. In this case Firebase will deliver remote message directly into your receiver and there you can create custom layout with your data.
I am sending push notifications using UrbanAirship API using java.
Here is the doc: http://docs.urbanairship.com/api/
I want to send a push notifications with custom key/value. For example, I want send to following to Android/iOS device
name: "Jack"
String appKey = "appKey";
String appSecret = "appSecret";
// Setup an authenticated APIClient with your application key and
// application master secret.
APIClient apiClient = APIClient.newBuilder()
.setKey(appKey)
.setSecret(appSecret)
.build();
// Setup a push payload to send to the API with our handy builders
PushPayload payload = PushPayload.newBuilder()
.setAudience(Selectors.all())
.setNotification(Notifications.notification("UA Push"))
.setDeviceTypes(DeviceTypeData.of(DeviceType.IOS))
.build();
// Try and send, handle anything that comes up
try {
APIClientResponse<APIPushResponse> response = apiClient.push(payload);
logger.info("Sent a push message!");
}
// Non 200 responses throw an APIRequestException. Check the documentation
// to debug your request.
catch (APIRequestException ex){
logger.error("Non 200 request, checking error details and taking action");
}
// An underlying error occurred, most likely outside of the scope of the
// UA library, do some HTTP debugging
catch (IOException e){
logger.error("Broken pipe what?");
}
Here is the code reference for android - https://github.com/urbanairship/java-library/blob/master/src/test/java/com/urbanairship/api/push/model/notification/android/AndroidDevicePayloadTest.java
How can i do send push notification with custom key/value using AndroidDevicePayload ?
You can create your notification like this:
public PushPayload createPushPayloadCustom(String namedUser, String message) {
Notification notification = Notification.newBuilder()
.addDeviceTypeOverride(DeviceType.IOS, IOSDevicePayload.newBuilder()
.setAlert(message)
.build())
.addDeviceTypeOverride(DeviceType.ANDROID, AndroidDevicePayload.newBuilder()
.setAlert(message)
.build())
.build();
return PushPayload.newBuilder()
.setAudience(Selectors.namedUser(namedUser))
.setNotification(notification)
.setDeviceTypes(DeviceTypeData.of(DeviceType.ANDROID, DeviceType.IOS))
.build();
}
You can add to the "extras" object any key/value:
DeviceTypeData deviceTypeData = DeviceTypeData.of(DeviceType.IOS, DeviceType.ANDROID);
IOSDevicePayload iosPayload = IOSDevicePayload.newBuilder()
.setAlert(message)
.addExtraEntry("custom_ios_key", "custom value for IOS")
.build();
AndroidDevicePayload androidPayload = AndroidDevicePayload.newBuilder()
.setAlert(message)
.addExtraEntry("custom_android_key", "custom value for Android")
.build();
PushPayload payload = PushPayload.newBuilder()
.setAudience(Selectors.namedUser(email))
.setNotification(Notifications.notification(iosPayload,androidPayload))
.setDeviceTypes(deviceTypeData)
.build();
Then in the received push, you will find the object:
For more details go to urbanairship official documentation
I'm trying to send a notification to my pebble watch. I'm using this code, which is basically the example from the website:
public void sendPebble(String title, String body) {
final Intent i = new Intent("com.getpebble.action.SEND_NOTIFICATION");
final Map<String, String> data = new HashMap<String, String>();
data.put("title", title);
data.put("body", body);
final JSONObject jsonData = new JSONObject(data);
final String notificationData = new JSONArray().put(jsonData).toString();
i.putExtra("messageType", "PEBBLE_ALERT");
i.putExtra("sender", "Test");
i.putExtra("notificationData", notificationData);
Log.d("Test", "Sending to Pebble: " + notificationData);
sendBroadcast(i);
}
I'm getting the message in LogCat, but no notification on the watch. The procedure seems simple enough, is there something too obvious I missed? Or is the documentation just incomplete?
Edit: The obvious questions:
Yes, the watch is connected
Yes, I have third party notifications enabled
Okay, this was my problem:
By default the Pebble app only sends notifications to the watch while the screen of the phone is off. For development I always have the screen active while the phone is connected via USB. So, the solution was: Enable the "Always send Notifications" option in the Pebble app.
Maybe this spares someone else a headache.