Notification setSound() doesn't seem to actually set a sound - android

I recently started coding my first android project including notifications (SDK 21 - Android 5)
Currently, I have a tiny little button, that creates a notification on click and sends it to the app itself. Sound foolish but the purpose is to test if a custom sound and vibrate pattern is used.
This is the notification that gets constructed on click:
Notification note = new Notification.Builder(this.requireContext(), "channel_id")
.setSmallIcon(R.mipmap.icon)
.setContentTitle("Title")
.setContentText("Text")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setVibrate(new long[] {500, 500, 500, 500, 500})
.setSound(SettingsHandler.getRingtoneUri(this.requireContext())
.setContentIntent(anyIntent)
.setAutoCancel(true)
.build();
SettingsHandler is a helper class I created to handle settings. Like switching vibration on and off or picking a ringtone. getRingtoneUri() does the following:
public synchronized static Uri getRingtoneUri(Context context) {
SharedPreferences prefs = context.getSharedPreferences("table_name", Context.MODE_PRIVATE);
return Uri.parse(prefs.getString("ringtone_uri_key", RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION).toString()));
}
When debugging this the result of getRingtoneUri is something like "content://media/internal/audio/media/31". This looks valid to me. However, in a later line, the sound property of the created notification is still null. Amy idea what I'm doing wrong? Thanks in forward.

try this:
Uri alarmSound = Uri.parse("android.resource://" + context.getPackageName() + "/raw/ding");
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, context.getString(R.string.checkout_channel));
mBuilder.setContentTitle(context.getString(R.string.passenger_name)).setContentText(context.getString(R.string.pit, name)).setSmallIcon(R.drawable.notification_icon).setSound(alarmSound);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
String channelDescription = "Checkout Channel";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
NotificationChannel notificationChannel = new NotificationChannel(context.getString(R.string.checkout_channel),
channelDescription, notifManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.GREEN);
notificationChannel.setShowBadge(true);
notificationChannel.setSound(alarmSound, audioAttributes);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(iUniqueId, notification);
You need to set the audioAttributes and create your notification channel. This works for me for all Android from 4.2 to 9

Related

custom push notification sound not working in android (FCM)

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.

Android multiple sound for notification

Am trying to produce two type of custom notification sound by adding .wav file in raw folder, when notification like job comes it produce job related notification sound in other case if notification like message comes it produce message related notification sound.
I set channel if for get the notification in Higher end device,but after creating the channel id am getting same notification sound when a notification comes based on which type of notification comes first.
onMessageReceived
String sound = data.get("sound");
Uri soundUri = Uri.parse("android.resource://" + getPackageName() + "/raw/" + sound);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
.setSmallIcon(getNotificationIconId())
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.setSound(soundUri)
.setContentIntent(pendingIntent)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(messageBody));
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O && notificationManager != null) {
int importance = android.app.NotificationManager.IMPORTANCE_HIGH;
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
NotificationChannel mChannel = new NotificationChannel(
getString(R.string.default_notification_channel_id), Constants.NOTIFICATION_CHANNEL_NAME_MESSAGE, importance);
mChannel.setSound(soundUri,audioAttributes);
notificationManager.createNotificationChannel(mChannel);
}
if (notificationManager != null) {
notificationManager.notify(messageId, notificationBuilder.build());
}
Manifest
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id"/>`enter code here`
You need to create two notification channels, each channel for each sound and assign the ID of the channels depending on the sound you want to reproduce.
It is explained in the documentation that once a channel is created it cannot be modified.

Custom notification sound not working in 5.0 and higher

I am trying to add custom sound to notification. Following is my code:
notificationSoundUri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.error);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("default",
"YOUR_CHANNEL_NAME",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("YOUR_NOTIFICATION_CHANNEL_DISCRIPTION");
mNotificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "default")
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setSmallIcon(R.mipmap.ic_launcher) // notification icon
.setContentTitle("BATTERY FULL") // title for notification
.setContentText("Battery is full. Please plug out the charger. Overcharging may decrease battery life span.")// message for notification
.setSound(notificationSoundUri) // set alarm sound for notification
.setAutoCancel(true); // clear notification after click
mNotificationManager.notify(1, mBuilder.build());
This code is working in pre-lollipop devices and not on Marshmallow. In Marshmallow, it is using phone's default notification sound. I am assuming this problem is for lollipop and higher devices. What am I missing here?
Had this issue for a few tries, it looks like NotificationCompat misses a method for sound on between androids 21 and 25, for notification to work you need to set the sound as this
val builder: Notification.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder(this, channelId1)
} else {
Notification.Builder(this)
}
...
val audioAttr = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM).build()
builder.setSound(
notification1Sound(), // custom uri
audioAttr)
I don't support versions prior lollipop so this works for me, for older version you might need to add a second version check
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder.setSound(
notification1Sound(),
audioAttr
)
} else {
builder.setSound(notification1Sound(), AudioManager.STREAM_ALARM)
}
You have to use Notification Channel whit Android O (https://developer.android.com/training/notify-user/channels).
This work only on API 26+ because the NotificationChannel class is new and not in the support library.
builder.setStyle(new NotificationCompat.InboxStyle());
The full code:
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Notifications Example")
.setContentText("This is a test notification");
Intent notificationIntent = new Intent(this, MenuScreen.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
builder.setAutoCancel(true);
builder.setLights(Color.BLUE, 500, 500);
long[] pattern = {500,500,500,500,500,500,500,500,500};
builder.setVibrate(pattern);
builder.setStyle(new NotificationCompat.InboxStyle());
Use these lines of code for custom sound
URI uri=Uri.parse("android.resource://"+context.getPackageName()+"/"+R.raw.FILE_NAME);//Here is FILE_NAME is the name of file that you want to play
builder.setSound(uri);
Don't forget to add notification channel
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
#SuppressLint("WrongConstant")
NotificationChannel channel = new NotificationChannel("XYZ", "ABC",NotificationManager.IMPORTANCE_MAX);
mNotificationManager.createNotificationChannel(channel);
}
mNotificationManager.notify(0, mBuilder.build());

Android 8 notifications setSound not working

I have the following code but everytime I just hear the default android sound.
// create channel
NotificationChannel channel = new NotificationChannel(ANDROID_CHANNEL_ID,
ANDROID_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
// Sets whether notifications posted to this channel should display notification lights
channel.enableLights(true);
// Sets whether notification posted to this channel should vibrate.
channel.enableVibration(true);
// Sets the notification light color for notifications posted to this channel
channel.setLightColor(Color.GREEN);
// Sets whether notifications posted to this channel appear on the lockscreen or not
//channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
Uri uri = Uri.parse("android.resource://"+this.getPackageName()+"/" + R.raw.aperturaabductores);
AudioAttributes att = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build();
channel.setSound(uri,att);
This is my sound pablomonteserin.es/aperturaabductores.wav
I tried to see the difference between your sound file and mine. I used Audacity software.
Your sound file has sampling rate 22050Hz while the sound files i use are sampled at 44100Hz. So i converted your sound file sampling rate to 44100Hz and used that as notification sound. Now it works.
The problem is with the sound file. May be it's new change in Android O because it's working fine on older Android version.
This is how to resample-
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
Notification.Builder notificationBuilder =
new Notification.Builder(MyApplication.getInstance().getApplicationContext(), NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(pTitle)
.setContentText(messageBody)
.setAutoCancel(true)
//.setPriority(Notification.PRIORITY_MAX) // this is deprecated in API 26 but you can still use for below 26. check below update for 26 API
//.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
AudioAttributes att = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build();
notificationChannel.setSound(defaultSoundUri,att);
notificationChannel.setDescription(messageBody);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
if (imageThumbnail != null) {
notificationBuilder.setStyle(new Notification.BigPictureStyle()
.bigPicture(imageThumbnail).setSummaryText(messageBody));
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
} else {
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(MyApplication.getInstance().getApplicationContext())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(pTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_MAX) // this is deprecated in API 26 but you can still use for below 26. check below update for 26 API
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
if (imageThumbnail != null) {
notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(imageThumbnail).setSummaryText(messageBody));
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

Android O reporting notification not posted to channel - but it is

Couple Android O notification questions:
1) I have created a Notification Channel (see below), am calling the builder with .setChannelId() (passing in the name of the channel I created, "wakey"; and yet, when I run the app, I get a message that I've failed to post a notification to channel "null". What might be causing this?
2) I suspect the answer to #1 can be found in the "log" that it says to check, but I've checked logcat & don't see anything about notifications or channels. Where is the log that it says to look in?
Here's the code I'm using to create the channel:
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence name = context.getString(R.string.app_name);
String description = "yadda yadda"
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL, name, importance);
channel.setDescription(description);
notificationManager.createNotificationChannel(channel);
Here's the code to generate the notification:
Notification.Builder notificationBuilder;
Intent notificationIntent = new Intent(context, BulbActivity.class);
notificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); // Fix for https://code.google.com/p/android/issues/detail?id=53313
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Intent serviceIntent = new Intent(context, RemoteViewToggleService.class);
serviceIntent.putExtra(WakeyService.KEY_REQUEST_SOURCE, WakeyService.REQUEST_SOURCE_NOTIFICATION);
PendingIntent actionPendingIntent = PendingIntent.getService(context, 0, serviceIntent, PendingIntent.FLAG_CANCEL_CURRENT);
_toggleAction = new Notification.Action(R.drawable.ic_power_settings_new_black_24dp, context.getString(R.string.toggle_wakey), actionPendingIntent);
notificationBuilder= new Notification.Builder(context)
.setContentTitle(context.getString(R.string.app_name))
.setContentIntent(contentIntent)
.addAction(_toggleAction);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationBuilder.setChannelId(NOTIFICATION_CHANNEL);
}
notificationBuilder.setSmallIcon(icon);
notificationBuilder.setContentText(contentText);
_toggleAction.title = actionText;
int priority = getNotificationPriority(context);
notificationBuilder.setPriority(priority);
notificationBuilder.setOngoing(true);
Notification notification = notificationBuilder.build();
notificationManager.notify(NOTIFICATION_ID, notification);
And here's the warning I'm getting:
I think I have learned a couple things that all add up to an answer:
I was using an emulator device, with an image that did not include the Play Store.
The version of Google Play Services on the image was not the latest, so I should have been getting a notification telling me I needed to upgrade. Since that notification didn't get applied to a channel, it didn't appear.
If I set logcat in Android Studio to "No Filters" instead of "Show only selected application", then I found the logs that pointed out that the notification in question was the Play Services "update needed" notification.
So, I changed to a image with the Play Store included, and it showed the notification properly (maybe the channel for that notification was to be set by the Play Store?), let me update to the latest Google Play Services, and I haven't seen that warning since.
So, long story short (too late) - with Android O, if you are using Google Play Services & testing on the emulator, choose an image with the Play Store included, or ignore the toast (good luck on that one!).
I had the same problem, and resolved it by using the constructor
new Notification.Builder(Context context, String channelId), instead of the one which is deprecated onAPI levels >=26 (Android O) :
new NotificationCompat.Builder(Context context)
The following code won't work if your notificationBuilder is built using the deprecated constructor :
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationBuilder.setChannelId(NOTIFICATION_CHANNEL);}
First create the notification channel:
public static final String NOTIFICATION_CHANNEL_ID = "4565";
//Notification Channel
CharSequence channelName = NOTIFICATION_CHANNEL_NAME;
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
then use the channel id in the constructor:
final NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
.setDefaults(Notification.DEFAULT_ALL)
.setSmallIcon(R.drawable.ic_timers)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setSound(null)
.setChannelId(NOTIFICATION_CHANNEL_ID)
.setContent(contentView)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setLargeIcon(picture)
.setTicker(sTimer)
.setContentIntent(pendingIntent)
.setAutoCancel(false);
You gotta create a channel before.
private void createNotificationChannel() {
// 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 = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
public void notifyThis(String title, String message) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.green_circle)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(0, mBuilder.build());
}
Finally you call this method:
createNotificationChannel();
notifyThis("My notification", "Hello World!");
create a notification using following code :
Notification notification = new Notification.Builder(MainActivity.this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.mipmap.ic_launcher)
.setChannelId(channelId)
.build();
not using :
Notification notification = new NotificationCompat.Builder(MainActivity.this)
.setContentTitle("Some Message")
.setContentText("You've received new messages!")
.setSmallIcon(R.mipmap.ic_launcher)
.setChannel(channelId)
.build();
You have to create a NotificationChannel first
val notificationChannel = NotificationChannel("channelId", "channelName", NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(notificationChannel);
This is the only way to show notification for API 26+
I was facing the same problem. It got resolved by creating a NotificationChannel and adding that newly created channel with the notification manager.
I would also like to add that you will receive this error if you're using Build tools v26+:
app/build.grade:
compileSdkVersion 26
buildToolsVersion "26.0.2"
defaultConfig {
targetSdkVersion 26
Downgrading to lowest version should work fine.

Categories

Resources