How to Make Push Notification With Specific Sound

How to make push notification with specific sound?

To combine the answers here and using the two answers from these questions:

  • How to add sound to notification?
  • How to get URI from an asset File?

Try this:

Uri sound = Uri.parse("file:///android_asset/hopo.mp3");

Notification noti = new Notification.Builder(MainActivity.this)
.setTicker("Calcupital")
.setContentTitle("Calcupital")
.setContentText("User Information has been updated successfully")
.setSmallIcon(R.drawable.login)

.setSound(sound);

.setContentIntent(pIntent).getNotification();

noti.flags = Notification.FLAG_AUTO_CANCEL;

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, noti);

Custom sound in Firebase push notification

I was also looking for the solution to custom sound for firebase notification in the android, And I have solved this problem through Notification Channel.

I have created one notification channel with custom sound, that sound plays after receiving notification in the application background state.

You can refer following links of the notification channel.

https://medium.com/exploring-android/exploring-android-o-notification-channels-94cd274f604c

https://developer.android.com/training/notify-user/channels

You need to put your mp3 file at /res/raw/ path.

Please find the code.

NotificationManager notificationManager = (NotificationManager) getActivity().getSystemService(NotificationManager.class); // If you are writting code in fragment

OR

NotificationManager notificationManager = (NotificationManager) getSystemService(NotificationManager.class); // If you are writting code in Activity

createNotificationChannel function

private void createNotificationChannel() { 
Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/" + R.raw.sample); //Here is FILE_NAME is the name of file that you want to play
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library if
(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
CharSequence name = "mychannel";
String description = "testing";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
NotificationChannel channel = new NotificationChannel("cnid", name, importance);
channel.setDescription(description);
channel.enableLights(true); channel.enableVibration(true);
channel.setSound(sound, audioAttributes);
notificationManager.createNotificationChannel(channel);
}
};

createNotificationChannel();

To achieve this you need to pass android_channel_id property in the firebase notification request object.

{
"notification": {
"body": "this is testing notification",
"title": "My App",
"android_channel_id": "cnid"
},
"to": "token"
}

Custom sound push notification does not work (Flutter)

Reading this it seems that it should be manage automatically (if you didn't use a notification builder) on Android but you have to specify the .mp3 extension too and put it inside notification field and not data one..

"sound": "alarm.mp3"

iOS behaves very differently under the hood but you can use a custom sound by setting the sound: field in the notification payload too. Anyway .mp3 is not a valid APN notification file format, and you need to specify also the file extention.

"sound": "filename.caf"

Follow Apple documentation in order to forge your custom sound file for your app.

mp3 is not a valid format

Preparing Custom Alert Sounds

Local and remote notifications can specify custom alert sounds to be
played when the notification is delivered. You can package the audio
data in an aiff, wav, or caf file. Because they are played by the
system-sound facility, custom sounds must be in one of the following
audio data formats:

  • Linear PCM

  • MA4 (IMA/ADPCM)

  • µLaw

  • aLaw

Place custom sound files in your app bundle or in the
Library/Sounds folder of your app’s container directory. Custom
sounds must be under 30 seconds when played. If a custom sound is
over that limit, the default system sound is played instead.

You can use the afconvert tool to convert sounds. For example, to
convert the 16-bit linear PCM system sound Submarine.aiff to IMA4
audio in a CAF file, use the following command in the Terminal app:

afconvert /System/Library/Sounds/Submarine.aiff ~/Desktop/sub.caf -d ima4 -f caff -v

For exampole to convert your mp3 file in a caf file you could type in terminal:

afconvert -f caff -d LEI16 alarm.mp3 alarm.caf

Read this doc in order to have a deep inside of all generic and specific notifciation payload fields.

UPDATE

I've tested the Android part and I can confirm that putting your .mp3 file in res/raw/ folder the sound is played as documented and expected.

That's my notification payload:

{
"to" : "my_device_token",
"collapse_key" : "type_a",
"priority" : "high",
"notification" : {
"body" : "Test Notification body for custom sound {{datestamp}}",
"title": "Custom sound alert.mp3",
"sound": "alert.mp3"
}
}

Sample Image

I've tested also the iOS version after converting .mp3 file to .caf file in that way:

afconvert -f caff -d LEI16 alert.mp3 alert.caf

the same json payload with the different filename works:

{
"to" : "my_device_token",
"collapse_key" : "type_a",
"priority" : "high",
"notification" : {
"body" : "Test Notification body for custom sound {{datestamp}}",
"title": "Custom sound alert.mp3",
"sound": "alert.caf"
}
}

Remember to add the file in your main bundle.

Sample Image

That works if the app is terminated or in background.

If you want to show an alert and play a sound when the app is in foreground you have to manage it on onMessage event like someone already have told you here, or you can use a platform-channel here to build your own notification with a Notification.Builder on Android and a UNNotificationCenter on iOS (for example).

UPDATE

This issue has been solved. See here the official comment:

Hey all /p>

As part of our roadmap (#2582) we've just shipped a complete rework of
the firebase_messaging plugin that aims to solve this and many other
issues.

If you can, please try out the dev release (see the migration guide
for upgrading and for changes) and if you have any feedback then join
in the discussion here.

Given the scope of the rework I'm going to go ahead and close this
issue in favor of trying out the latest plugin.

Thanks everyone /p>

Android Notification Sound

What was missing from my previous code:

Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(alarmSound);

Send GCM Push Notification to android with custom sound

No need to specify extension of file resides under res/raw folder. I Just put "notify.mp3" in res/raw folder and modified code as following:

'sound' => "notify"

It worked for me.

Thanks :)

react-native-push-notification custom sound not working when android app is killed

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!



Related Topics



Leave a reply



Submit