Notification custom sound and vibrate not working? - android

I have an app that receives notification, all is working. However, the custom sound and vibration is not working. I'm testing it on Android 9 pie.
Uri sound = Uri.parse("android.resource://" +getApplicationContext().getPackageName()+ "/" +R.raw.siren); //ContentResolver.SCHEME_ANDROID_RESOURCE +
String NOTIFICATION_CHANNEL_ID = "com.example.bantay.bantay.test";
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setWhen(System.currentTimeMillis());
notificationBuilder.setSmallIcon(R.drawable.marikinalogo);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(body);
notificationBuilder.setSound(sound);
notificationBuilder.setVibrate(new long[]{500, 1000, 500, 1000});
if(title.toLowerCase().contains("1")){
notificationBuilder.setContentIntent(pendingIntent);
}
else{
notificationBuilder.setContentIntent(pendingIntent3);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification", NotificationManager.IMPORTANCE_HIGH);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{500, 1000, 500, 1000});
notificationChannel.setSound(sound, audioAttributes);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(0, notificationBuilder.build());
I don't know my errors. Does the NOTIFICATION_CHANNEL_ID affect the behavior of the notification?

I am using MediaPlayer for custom sound. And This is Working fine for me. This is working for all devices.
private MediaPlayer player;
For play custom sound:
try {
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.siren);
player = MediaPlayer.create(this, uri);
player.setLooping(true); // This will play sound in repeatable mode.
player.start();
// mBuilder.setSound(uri);
} catch (Exception e) {
e.printStackTrace();
}
For stop sound:
if (player != null)
player.stop();
This is working for me. Hope this will also helps you.

Related

Android Custom Notification sound is Not working?

I am getting the custom sound name from the notification and added conditions based on key but always sound only playing in my notification.
I want to play different sounds based on sound keys and how to handle anyone have ideas to help the same.
if (playOrderAssignmentTone) {
if(key.equalsIgnoreCase("sound")){
alarmSound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.sound);
} else {
alarmSound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.sound2);
}
} else {
alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
} catch (Exception e) {
LoggerUtility.PrintTrace(e);
FirebaseCrashlytics.getInstance().log(e.getMessage());
FirebaseCrashlytics.getInstance().recordException(e);
alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Notification Builder
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, CHANNEL_ONE_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(notificationTitle)
.setContentText(notificationBody)
//Optional fields
.setPriority(NotificationCompat.PRIORITY_MAX)
.setCategory(NotificationCompat.CATEGORY_STATUS)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setTicker(notificationTicker)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setWhen(System.currentTimeMillis())
//.setSound(alarmSound)
//.setShowWhen(true)
.setOngoing(isOngoing);
// Setting notification sound based on channel id
if (!CHANNEL_ONE_ID.equalsIgnoreCase("auto")) {
notificationBuilder.setSound(alarmSound);
}
So the issue with your code is you need to make separate notification channels for different sounds to work. Above is the code to attach a sound to the notification channel.
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
Uri audio = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + File.pathSeparator + File.separator
+ File.separator + getApplicationContext().getPackageName() + File.separator + R.raw.notification);
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION).build();
channel.setSound(audio, attributes);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
}
So when you want to play some specific sound with a notification use that notification CHANNEL_ID with the notification builder.
You have to call setSound() method on NotificationChannel instance.
val audioAttributes = AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build()
val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH).apply {
setSound(soundUri, audioAttributes)
}
select notification tone from your mobile:
Uri ringtone=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);;
Intent intent=new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, ringtone);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, ringtone);
((Activity) getContext()).startActivityForResult(intent , 1);
get ringtone path in onActivity result:
if (resultCode == MainActivity.RESULT_OK && requestCode == 1) {
uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
path = uri.toString();
}
saving this path in sqlite database and retrive from in service
when you trigger your notification play this sound just once:
Uri uri;
uri = Uri.parse(myDb.alarmGetRingtone(requestcode));
r = RingtoneManager.getRingtone(getApplicationContext(), uri);
r.play();
I Hope This Code Will Help You
Thank You

Push Notifications don't vibrate when app is closed

On Android 10, when I receive push notification, the vibration only works if app is opened. If it's in background or closed, vibration doesn't work (but notification get's through and sound works). Is this a bug? Couldn't find it in Google's bug-tracker though.
I send the push notification from our server with data payload, which ensures onMessageReceived() gets called even if app is in background. And it does, I can debug it.
Here's how notification channel is created:
NotificationChannel mChannelUp = new NotificationChannel(CHANNEL_ID_ALERTS_UP, getApplicationContext().getString(R.string.alerts_up), NotificationManager.IMPORTANCE_HIGH);
mChannelUp.enableLights(true);
mChannelUp.enableVibration(true);
// mChannelUp.setVibrationPattern(new long[]{500, 250, 500, 250}); // doesn't help
mChannelUp.setLightColor(Color.BLUE);
AudioAttributes audioAttributesUp = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT)
.build();
mChannelUp.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/" + R.raw.notif_sound_up), audioAttributesUp);
notificationManager.createNotificationChannel(mChannelUp);
And the notification itself:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this, CHANNEL_ID_ALERTS_UP)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_notif)
.setColor(ContextCompat.getColor(this, R.color.colorPrimary))
.setLargeIcon(logo)
.setVibrate(new long[]{250, 500, 250, 500})
.setLights(Color.parseColor("#039be5"), 500, 500)
.setContentTitle("some title")
.setContentText("some content")
.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/" + R.raw.notif_sound_up));
mBuilder.setContentIntent(resultPendingIntent);
Notification notif = mBuilder.build();
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(notificationId, notif);
You need to call the vibration service.
vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
vibrator.vibrate(2000);
if Your device set Automatically miscellaneous notification channel in notification channel
you can try Firebase default Chanel
public static String NOTIFICATION_CHANNEL_ID ="fcm_fallback_notification_channel";
Channel
NotificationManager notificationManager = mContext.GetSystemService(Context.NotificationService) as NotificationManager;
if (global::Android.OS.Build.VERSION.SdkInt >= global::Android.OS.BuildVersionCodes.O)
{
NotificationImportance importance = global::Android.App.NotificationImportance.High;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, title, importance);
notificationChannel.EnableLights(true);
notificationChannel.EnableVibration(true);
notificationChannel.SetSound(sound, alarmAttributes);
notificationChannel.SetShowBadge(true);
notificationChannel.Importance = NotificationImportance.High;
notificationChannel.SetVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });
if (notificationManager != null)
{
mBuilder.SetChannelId(NOTIFICATION_CHANNEL_ID);
notificationManager.CreateNotificationChannel(notificationChannel);
}
}
notificationManager.Notify(0, mBuilder.Build());
my class :
class NotificationHelper : INotification
{
private Context mContext;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mBuilder;
public static String NOTIFICATION_CHANNEL_ID = "fcm_fallback_notification_channel";
public NotificationHelper()
{
mContext = global::Android.App.Application.Context;
}
public void CreateNotification(String title, String message)
{
try
{
var intent = new Intent(mContext, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
intent.PutExtra(title, message);
var pendingIntent = PendingIntent.GetActivity(mContext, 0, intent, PendingIntentFlags.OneShot);
var sound = global::Android.Net.Uri.Parse(ContentResolver.SchemeAndroidResource + "://" + mContext.PackageName + "/"+Resource.Raw.notification);//add sound
// Creating an Audio Attribute
var alarmAttributes = new AudioAttributes.Builder()
.SetContentType(AudioContentType.Sonification)
.SetUsage(AudioUsageKind.Notification).Build();
mBuilder = new NotificationCompat.Builder(mContext);
mBuilder.SetSmallIcon(Resource.Drawable.INH_ICON1);
mBuilder.SetContentTitle(title)
.SetSound(sound)
.SetAutoCancel(true)
.SetContentTitle(title)
.SetContentText(message)
.SetChannelId(NOTIFICATION_CHANNEL_ID)
.SetPriority((int)NotificationPriority.High)
.SetLights(65536, 1000, 500)
//.SetColor(Resource.Color.)
.SetVibrate(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 })
.SetDefaults((int)NotificationDefaults.Sound | (int)NotificationDefaults.Vibrate)
.SetVisibility((int)NotificationVisibility.Public)
.SetSmallIcon(Resource.Drawable.INH_ICON1)
.SetContentIntent(pendingIntent);
NotificationManager notificationManager = mContext.GetSystemService(Context.NotificationService) as NotificationManager;
if (global::Android.OS.Build.VERSION.SdkInt >= global::Android.OS.BuildVersionCodes.O)
{
NotificationImportance importance = global::Android.App.NotificationImportance.High;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, title, importance);
notificationChannel.EnableLights(true);
notificationChannel.EnableVibration(true);
notificationChannel.SetSound(sound, alarmAttributes);
notificationChannel.SetShowBadge(true);
notificationChannel.Importance = NotificationImportance.High;
notificationChannel.SetVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });
if (notificationManager != null)
{
mBuilder.SetChannelId(NOTIFICATION_CHANNEL_ID);
notificationManager.CreateNotificationChannel(notificationChannel);
}
}
notificationManager.Notify(0, mBuilder.Build());
}
catch (Exception ex)
{
//
}
}
}
By the reference of Firebase, when your app is in the background, the notification is delivered to the device’s system tray. A user tap on a notification opens the app launcher by default.
Messages with both notification and data payload, when received in the background. In this case, the notification is delivered to the device’s system tray, and the data payload is delivered in the extras of the intent of your launcher Activity. That time vibration could not happen.
You can try to wake up the application when u received a notification. That might help you.
Firebase Reference
Android Pie And Newer version have some limitations. Check this reference
Suggesting to question here: https://eu.community.samsung.com/t5/galaxy-s10e-s10-s10-s10-5g/s10-has-stopped-vibrating-when-reciving-notifications/m-p/1567092
Try heading to: Settings > Sound and vibration > Vibration intensity > Turn all options to max.
I've now noticed this in the Logcat:
Ignoring incoming vibration as process with uid = 10587 is background,
usage = USAGE_NOTIFICATION_EVENT
To make vibration work even when app in background, you need to use AudioAttributes.USAGE_NOTIFICATION (USAGE_NOTIFICATION_EVENT won't work!) AND also setVibrationPattern on channel:
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
NotificationChannel mChannelUp = new NotificationChannel(CHANNEL_ID_ALERTS_UP, getApplicationContext().getString(R.string.alerts_up), NotificationManager.IMPORTANCE_HIGH);
mChannelUp.enableLights(true);
mChannelUp.enableVibration(true);
mChannelUp.setVibrationPattern(new long[]{0, 300, 250, 300, 250, 300});
mChannelUp.setLightColor(Color.BLUE);
mChannelUp.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/" + R.raw.notif_sound_up), audioAttributes);
notificationManager.createNotificationChannel(mChannelUp);
Now vibration works when app in background too.
Thanks to ijigarsolanki's answer which helped me realize this.

Notification sound is not working in second attempt - Android Studio

I've developed an android app in which i have used opentok videoconference call functionality. I'm getting videocall notification through firebase push notification. But when i'm installing an app first time it is getting sound on notification then when i accept and enters into another activity's videoconference screen after that on next call notification its only vibrate not rings sound.
Below is my notification code snippet:
MyFirebaseMessagingServie.class
private void sendCallNotification(int status, String message, int queryId) {
saveNotificationLog(status, queryId);
long[] vibrate = new long[]{1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000};
final UserManager userManager = new UserManager(getApplicationContext());
boolean isLoggedIn = userManager.isLoggedIn().get();
Intent notificationIntent = isLoggedIn ? new Intent(this, HomeDoctorView.class) : new Intent(this, LoginView.class);
if (status == 6 || status == 7) {
notificationIntent.putExtra(Params.INTENT.SHOULD_UDPATE, true);
}
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri defaultSoundUri = Uri.parse("android.resource://com.myapplication.app/" + R.raw.iphone_ringtone);
Utils.printLog("FireBaseMessagingService", defaultSoundUri.toString());
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, CALL_CHANNEL)
.setContentTitle(getString(R.string.app_name))
.setContentText(message)
.setSound(defaultSoundUri)
.setVibrate(vibrate)
.setAutoCancel(false)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentIntent(pendingIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationBuilder.setSmallIcon(R.drawable.ic_notification);
notificationBuilder.setColor(ContextCompat.getColor(this, R.color.cerulean));
} else {
notificationBuilder.setSmallIcon(R.drawable.ic_notification);
}
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (notificationManager.getNotificationChannel(CALL_CHANNEL) == null) {
notificationManager.createNotificationChannel(Utils.createNotifChannel(this, defaultSoundUri, CALL_CHANNEL));
}
}
notificationManager.notify(notificationId, notificationBuilder.build());
}
Utils.java
#RequiresApi(Build.VERSION_CODES.O)
public static NotificationChannel createNotifChannel(Context context, Uri defaultSoundUri, String channelId) {
String channelName = channelId.equals("call_channel") ? "Call Alerts" : "Notification Alerts";
NotificationChannel channel = new NotificationChannel(channelId,
channelName, NotificationManager.IMPORTANCE_HIGH);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.build();
if (channelId.equals("call_channel")) {
channel.setDescription("Alerts related to calls");
channel.setVibrationPattern(new long[]{1000, 1000, 1000, 1000, 1000, 1000, 1000});
channel.setBypassDnd(true);
channel.setSound(defaultSoundUri, audioAttributes);
channel.enableVibration(true);
channel.enableLights(true);
channel.setShowBadge(false);
} else {
channel.setDescription("Alerts related to prescription, scheduled appointments, etc.");
channel.setVibrationPattern(new long[]{500, 500, 500, 500});
channel.setBypassDnd(true);
channel.setSound(defaultSoundUri, audioAttributes);
channel.enableVibration(true);
channel.enableLights(true);
channel.setShowBadge(false);
}
NotificationManager manager = context.getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
Log.d("CHANNEL", "createNotifChannel: created " + channelId + "\n" + defaultSoundUri);
return channel;
}

Notification custom sound play in foreground but not playing while app in background

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.

Android notification setSound is not working

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);

Categories

Resources