addSound
Adds a sound to the notification.
Configures the audio alert that plays when the notification is displayed. You can use the default system sound, a custom sound from your app resources, or disable sound entirely.
Sound File Locations: Custom sounds should be placed in:
- res/raw/ directory (recommended)
- assets/www/res/ directory
Android 8.0+ Note: Sound settings are controlled by notification channels and cannot be changed after the channel is created. Example - Use default system sound:
public Notification onGenerateNotification(@NonNull PushMessage data) {
String channelId = addChannel(data);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
getApplicationContext(), channelId)
.setContentTitle(data.getHeader())
.setContentText(data.getMessage())
.setSmallIcon(R.drawable.ic_notification);
Notification notification = builder.build();
// Use default system sound
addSound(notification, null);
return notification;
}
Content copied to clipboard
public Notification onGenerateNotification(@NonNull PushMessage data) {
String channelId = addChannel(data);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
getApplicationContext(), channelId)
.setContentTitle(data.getHeader())
.setContentText(data.getMessage())
.setSmallIcon(R.drawable.ic_notification);
Notification notification = builder.build();
// Use custom sound from res/raw/notification_sound.mp3
addSound(notification, "notification_sound");
return notification;
}
Content copied to clipboard
public Notification onGenerateNotification(@NonNull PushMessage data) {
String channelId = addChannel(data);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
getApplicationContext(), channelId)
.setContentTitle(data.getHeader())
.setContentText(data.getMessage())
.setSmallIcon(R.drawable.ic_notification);
Notification notification = builder.build();
// Check custom data for message type
String customData = data.getCustomData();
if (customData != null && customData.contains("urgent")) {
addSound(notification, "urgent_alert"); // Urgent sound
} else if (customData != null && customData.contains("silent")) {
addSound(notification, ""); // No sound
} else {
addSound(notification, data.getSound()); // Use payload sound
}
return notification;
}
Content copied to clipboard
Parameters
notification
The notification to add sound to
sound
Sound resource name from res/raw or assets/www/res directory.If null or file doesn't exist, default system sound will be played.If empty string, no sound will be played.