sound = Uri.parse("file://" + audioFilePath.getAbsolutePath());
/*sound = Uri.fromFile(audioFilePath);*/
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this);
mBuilder
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(title)
.setContentText(description)
.setContentIntent(resultPendingIntent)
.setSound(sound);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mBuilder.setPriority(Notification.PRIORITY_HIGH);
}
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
The sound file is present in local storage. Notification working properly but sound doesn't play. I tried both way to parse Uri from file path.
If you put your sound in your resource folder (which you should do anyway for notification sounds) and use Notification.Builder instead of NotificationCompat.Builder, you should be able to access it like this:
Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
getPackageName() + "/" + R.raw.name_of_sound);
Notification.Builder mBuilder =
new Notification.Builder(this);
mBuilder
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(title)
.setContentText(description)
.setContentIntent(resultPendingIntent)
.setSound(sound);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mBuilder.setPriority(Notification.PRIORITY_HIGH);
}
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
Source
Related
Be informed we are trying to send push notification to a device with custom sound. The custom mp3 file (120 seconds) is stored in res/raw file. The notification is sent successfully, but the sound never plays out even after many tries. The code is as given below:
Update:Based on suggestion given in the comments, created a notificationchannel and set the sound in it, but still its not working. Worse, unable to build apk at all.
Uri soundUri= Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + BuildConfig.APPLICATION_ID + "/" + R.raw.adhan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, MainActivity.asw_fcm_channel)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent);
Notification noti = notificationBuilder.build();
noti.flags = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.FLAG_AUTO_CANCEL;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel("345",
"new",
NotificationManager.IMPORTANCE_HIGH);
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
// Configure the notification channel.
mChannel.setDescription(message);
mChannel.enableLights(true);
mChannel.enableVibration(true);
mChannel.setSound(soundUri, attributes); // This is IMPORTANT
if (NotificationManager != null)
NotificationManager.createNotificationChannel(mChannel);
}
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notification_id, notificationBuilder.build());
We are at loss as where we are going wrong. Please guide us as how we solve this issue.
I have implemented custom view for firebase push notification. For custom view we need to remove "notification" key from push Json so that it can be handled even when app is closed like below:
{
"data": {
"detail": {
}
},
"to": ""
}
For creating custom notification I used below code:
private void generateNotification(String title, String message, Intent intent) {
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
String channelId = getString(R.string.default_notification_channel_id);
PendingIntent pendingIntent = PendingIntent.getActivity(this, notificationCount, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
/*
* Custom notification layout
* */
String notificationHeaderText = getResources().getString(R.string.app_name) + " \u2022 "
+ DateUtils.formatDateTime(this, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME);
RemoteViews collapsedView = new RemoteViews(getPackageName(), R.layout.view_collapsed_notification);
collapsedView.setTextViewText(R.id.timestamp, notificationHeaderText);
collapsedView.setTextViewText(R.id.content_title, title);
collapsedView.setTextViewText(R.id.content_text, message);
RemoteViews expandedView = new RemoteViews(getPackageName(), R.layout.view_expanded_notification);
expandedView.setTextViewText(R.id.timestamp, notificationHeaderText);
expandedView.setTextViewText(R.id.content_title, title);
expandedView.setTextViewText(R.id.notification_message, message);
Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"+ getApplicationContext().getPackageName() + "/" + R.raw.footer_click);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_inkclick_logo_colored)
.setSound(soundUri)
.setGroup(GROUP_KEY_INKCLICK)
.setAutoCancel(true)
.setGroupSummary(true)
.setCustomContentView(collapsedView)
.setCustomBigContentView(expandedView)
.setContentIntent(pendingIntent);
notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (manager != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
getResources().getString(R.string.default_notification_channel_id), NotificationManager.IMPORTANCE_HIGH);
channel.enableLights(true);
channel.setLightColor(Color.MAGENTA);
channel.setVibrationPattern(new long[]{0, 1000/*, 500, 1000*/});
channel.enableVibration(true);
channel.setShowBadge(true);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
channel.setSound(soundUri, audioAttributes);
manager.createNotificationChannel(channel);
}
manager.notify(0, notificationBuilder.build());
}
else {
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (manager != null) {
manager.notify(0, notificationBuilder.build());
}
}
notificationCount += 1;
}
I have added channel.setShowBadge(true); after reading the official notification badge documentation here as well as other answers on stackoverflow like this and this.
I have also tried uninstalling the app and restarting the device but the badge is not showing.
Device is running on API 28(Pie).
You can set style by adding below line
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
add this code
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_inkclick_logo_colored)
.setSound(soundUri)
.setGroup(GROUP_KEY_INKCLICK)
.setAutoCancel(true)
.setGroupSummary(true)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(collapsedView)
.setCustomBigContentView(expandedView)
.setContentIntent(pendingIntent);
notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
You can set the style of the Android notification badge like this:
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
The overall code can look like this:
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_inkclick_logo_colored)
.setSound(soundUri)
.setGroup(GROUP_KEY_INKCLICK)
.setAutoCancel(true)
.setGroupSummary(true)
.setCustomContentView(collapsedView)
.setCustomBigContentView(expandedView)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setContentIntent(pendingIntent);
notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
You need to specify the title or text (setContentTitle or setContentText). Because Android SDK uses it to describe notification in the window which appears when you long-click to the app icon. I don't know why this is not specified in the documentation, but it works this way.
I am adding custom sound for my application. The custom ringtone is playing when the application is in the foreground but the custom sound is not playing when the application is in background.
private void sendMyNotification(String message) {
Intent intent = new Intent(this, BaseActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri soundUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.ring);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "CH_ID")
.setSmallIcon(R.mipmap.iconfinal)
.setContentTitle(getString(R.string.app_name))
.setContentText(message)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
if(soundUri != null){
// Changing Default mode of notification
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
// Creating an Audio Attribute
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
// Creating Channel
NotificationChannel notificationChannel = new NotificationChannel("CH_ID","Testing_Audio",NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setSound(soundUri,audioAttributes);
mNotificationManager.createNotificationChannel(notificationChannel);
}
}
mNotificationManager.notify(1, notificationBuilder.build());
}
First you need to pass your sound file name from server side.
like below example:
{
"to": "firebase_notification_token",
"notification": {
"title": "Push notification title",
"body": "Push body",
"sound": "filename", <-- point to src/res/raw/filename.mp3
}
}
You need to add below code to play custom sound while app is in background.
val channelId = getString(R.string.app_name)
val NOTIFICATION_SOUND_URI =
Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + BuildConfig.APPLICATION_ID + "/" + R.raw.filename)
val notificationBuilder = NotificationCompat.Builder(this, channelId)
val notification: Notification
notification = notificationBuilder.setSmallIcon(R.drawable.ic_logo_white).setTicker(getString(R.string.app_name)).setWhen(0)
.setAutoCancel(true)
.setContentTitle(getString(R.string.app_name))
.setSound(NOTIFICATION_SOUND_URI)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(messageBody)
.build()
For more detail refer to this Document.
Thanks to Ilya Eremin for great article.
In my hybrid Cordova Android app targeting API 23+ I want to use a custom sound for notifications. To that end I have done the following
In plugin.xml file for the single custom plugin I use in the app I declare <resource-file src="src/android/res/unysound.mp3" target="res/raw/mysound.mp3" />'.
Opening the APK as a zip archive I see that the mp3 file has in fact ended up in `res/raw/mysound.mp3'.
- When building the notification I do the following
Notification notification = new Notification.Builder(context)
.setDefaults(0) //turns off ALL defaults
.setVibrate(vibrate) /sets to vibrate
....
.setSound(uri).build();
where
Uri uri = Uri.parse("android.resource://" + ctxt.getPackageName() + "/raw/mysound.mp3");
This appears to be the recipe indicated in a number of articles I find on a spot of googling and even in other threads on SO. And yet, when I issue a notification I do not hear the expected sound. What might I be doing wrong?
The answer below does not help since in the context of my hybrid Cordova app with a custom plugin attempting to build the APK throws up an error along the lines of class R not known/found...
below code will help you:
String CHANNEL_ID="1234";
Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"+ getApplicationContext().getPackageName() + "/" + R.raw.mysound);
NotificationManager mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
//For API 26+ you need to put some additional code like below:
NotificationChannel mChannel;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mChannel = new NotificationChannel(CHANNEL_ID, Utils.CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
mChannel.setLightColor(Color.GRAY);
mChannel.enableLights(true);
mChannel.setDescription(Utils.CHANNEL_SIREN_DESCRIPTION);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
mChannel.setSound(soundUri, audioAttributes);
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel( mChannel );
}
}
//General code:
NotificationCompat.Builder status = new NotificationCompat.Builder(getApplicationContext(),CHANNEL_ID);
status.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.logo)
//.setOnlyAlertOnce(true)
.setContentTitle(getString(R.string.app_name))
.setContentText(messageBody)
.setVibrate(new long[]{0, 500, 1000})
.setDefaults(Notification.DEFAULT_LIGHTS )
.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE+ "://" +mContext.getPackageName()+"/"+R.raw.apple_ring))
.setContentIntent(pendingIntent)
.setContent(views);
mNotificationManager.notify(major_id, status.build());
where mysound is my ringtone which is put under res/raw folder.
Note: you have to only put name of ringtone without extension like raw/mysound
Note: In Android Oreo you must change your channel ID to changes take effect. And before Oreo version, using ".setDefaults()" seens prevent custom sound to play.
Try clearing data (or fresh install)
Trying this again
The settings are set the first time you create the channel and then not modified unless you do it manually by fresh install or clearing data.
For more info on this read the top answer here:
Android Oreo notification keep making Sound even if I do not set sound. On Older version, works perfectly
For API 26+ you need to set the sound on the notification channel:
Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"+ getApplicationContext().getPackageName() + "/" + R.raw.siren);
NotificationManager mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel mChannel;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mChannel = new NotificationChannel(Utils.CHANNEL_SIREN_ID, Utils.CHANNEL_SIREN_NAME, NotificationManager.IMPORTANCE_HIGH);
mChannel.setLightColor(Color.GRAY);
mChannel.enableLights(true);
mChannel.setDescription(Utils.CHANNEL_SIREN_DESCRIPTION);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
mChannel.setSound(soundUri, audioAttributes);
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel( mChannel );
}
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, Utils.CHANNEL_SIREN_ID)
.setSmallIcon(R.drawable.ic_stat_maps_local_library)
.setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(), R.mipmap.ic_launcher))
.setTicker(title)
.setContentTitle(contentTitle)
.setContentText(contentText)
.setAutoCancel(true)
.setLights(0xff0000ff, 300, 1000) // blue color
.setWhen(System.currentTimeMillis())
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
mBuilder.setSound(soundUri);
}
int NOTIFICATION_ID = 1; // Causes to update the same notification over and over again.
if (mNotificationManager != null) {
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
you can call this method while handling notification
public void playNotificationSound() {
try {
Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
+ "://" + mContext.getPackageName() + "/raw/notification");
Ringtone r = RingtoneManager.getRingtone(mContext, alarmSound);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
Notification.Builder builder = new Notification.Builder(context);
builder.setContentTitle(mTitle);
builder.setContentText(mContentText);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
builder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
builder.setDefaults(Notification.DEFAULT_ALL);
Use this to work with sound, I hope it will solve your problem, Cheers!
Use this for setting sound
Uri defaultSoundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + mContext.getPackageName() + "/raw/mysound");
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(mContext)
.setContentIntent(mainPIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher))
.setContentTitle("" + title)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentText("" + body);
NotificationManager mNotificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(title, NOTIFICATION_ID, mBuilder.build());
You are accessing the sound in a subfolder in the resources
change the source of your uri to
Uri uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.siren);
For the default sound, use:
notification.defaults |= Notification.DEFAULT_SOUND;
I am not sure but i think issue is that you are doing the wrong way "/raw/mysound.mp3 :
Uri uri = Uri.parse("android.resource://" + ctxt.getPackageName() + "/raw/mysound.mp3");
First add the permission in manifest : uses-permission android:name="android.permission.VIBRATE" />
then you can set the default sound like :-
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);
and for vibration:
mBuilder.setVibrate(new long[] { 1000, 1000});
for custom sound, put mp3 file on this path:Res\raw\sound.mp3
and then
Notification notification = builder.build();
notification.sound = Uri.parse("android.resource://"
+ context.getPackageName() + "/" + R.raw.sound);
When the notification is received I dont get the sound and the vibration. For information phone is not in mute mode.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setContentText(message)
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
.setContentIntent(pendingIntent);
long[] pattern = {500,500,500};
builder.setVibrate(pattern);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(alarmSound);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0,builder.build());