How to set notification with custom sound in android - android

I copied the mp3 (kalimba.mp3) file into the raw folder in the res folder. But when the notification is triggered it produces the default sound.
This is how I make a notification:
protected void GenerateNotify() {
NotificationManager myNotificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification=new Notification(android.R.drawable.ic_btn_speak_now,"hi",100);
Intent intent=new Intent(getApplicationContext(),as.class);
PendingIntent contentintent=PendingIntent.getBroadcast(getApplicationContext(),0, intent, 0);
notification.setLatestEventInfo(getApplicationContext(), "Hi","date", contentintent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.sound = Uri.parse("android.resource://com.example.serviceproject/" + R.raw.kalimba);
myNotificationManager.notify(NOTIFICATION_ID,notification);
}

notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notifysnd);
notification.defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE;
if defined DEFAULT_SOUND, then the default sound overrides any sound

R.raw.kalimba is an integer resource ID; you want the name of the sound resource in that Uri. So try:
notification.sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
+ "://" + getPackageName() + "/raw/kalimba");

Try this:
Uri sound = Uri.parse("android.resource://" + context.getPackageName() + "/raw/notifysnd);
notification.setSound(sound);

You should replace this line:
notification.sound = Uri.parse("android.resource://com.example.serviceproject/" + R.raw.kalimba);
with this:
notification.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/kalimba"));
or in some cases:
notification.sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/kalimba");

I make this static function in HelperClass.java
public static void givenotification(Context context,String message) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, DesireActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notification notification = new Notification();
NotificationCompat.Builder builder;
builder = new NotificationCompat.Builder(context);
notification = builder.setContentIntent(pendingIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.setTicker(context.getString(R.string.app_name)).setWhen(System.currentTimeMillis())
.setAutoCancel(true).setContentTitle(context.getString(R.string.app_name))
.setContentText(message).build();
notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.kalimba);
notificationManager.notify(1, notification);
}
Then any Activity like in MainActivity
HelperClass.givenotification(MainActivity.this,"Your Notification Message");
OR in fragment
HelperClass.givenotification(getActivity(),"Your Notification Message");
Hope this help someone.

I have implemented this way to set custom Notification sound in my app.
int notificationID=001;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setSmallIcon(R.drawable.room);
mBuilder.setContentTitle("Room Rent , Pay Room Rent");
mBuilder.setContentText("Hi, Its time to pay your Room Rent!");
mBuilder.setAutoCancel(true);
mBuilder.setColor(getResources().getColor(R.color.colorViolet));
mBuilder.setSound(Uri.parse("android.resource://com.roommanagement.app/" + R.raw.notification_sound));
if (mNotificationManager!=null){
mNotificationManager.notify(notificationID, mBuilder.build());
}
Hop this will help you.Thanks...

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

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

Android Notification Builder don't play custom sound

I post the code that I use to retrieve a message and display a notification from firebase. I receive the notification with the correct text and title, but this notification is silent. Even I set the default sound or the custom sound.
How do I play the correct sound?
public class NotificationMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d("sb.fbv", "NotificationMessaginService.onmessageReceived");
String title = remoteMessage.getNotification().getTitle();
String subText = remoteMessage.getNotification().getBody();
String message = remoteMessage.getData().get("subtext");
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder nb = new NotificationCompat.Builder(this);
nb.setContentTitle(title);
nb.setSubText(message);
nb.setContentText(subText);
nb.setSmallIcon(R.drawable.notificavedelago);
nb.setAutoCancel(true);
nb.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
nb.setLights(Color.BLUE, 3000, 3000);
//SOUND DEFAULT
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
nb.setSound(alarmSound);
//CUSTOM SOUND
//Uri customSound= Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.sound);
//nb.setSound(customSound);
nb.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, nb.build());
}
}
To set a custom alarm sound in your notification builder, do this:
int soundResId = R.raw.myCustomSoundResource;
Uri soundUri = Uri.parse("android.resource://" + context.getPackageName() + "/" + soundResId);
nb.setSound(soundUri, AudioManager.STREAM_ALARM);
using the Resource ID number of a file like res/raw/myCustomSoundResource.ogg. It can be in any of these supported file formats.

How to debug if android.resource:// does exist when having Uri to that resource

I am working on push notifications with Android studio with my phone plugged in via USB as debugging device and notifications are coming through just fine custom text set, etc. However when I try to set custom sound by using
Uri defaultSoundUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.alarm);
which then evaluates to android.resource://gcm.play.android.samples.com.gcmquickstart/2131099648 it does not play ball.
My guess is that sound file is not there and it simply fails silently.
Code:
private void sendNotification(String message) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.alarm);
// RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle(message)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
How would I debug the application where by having Url I could confirm if resource is there or not?

Custom notification sound not playing

I'm trying to make a custom sound play on a status bar notification. The .mp3 file is in res/raw/. But when I notify the user the sound is not played. I've tryied with MediaPlayer, and it works, but I dont want to make it play with MediaPlayer.
Here is my method:
public void showNotification()
{
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.feedback; // icon from resources
CharSequence tickerText = mContext.getString(R.string.statusbar_notification); // ticker-text
long when = System.currentTimeMillis(); // notification time
Context context = getApplicationContext(); // application Context
CharSequence contentTitle = mContext.getString(R.string.statusbar_notification); // message title
CharSequence contentText = mContext.getString(R.string.statusbar_notificatione_detailed); // message text
Intent notificationIntent = new Intent(mContext, Main.class);
PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0);
// the next two lines initialize the Notification, using the configurations above
Notification notification = new Notification(icon, tickerText, when);
//notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.sound = Uri.parse("android.resource://" + getPackageName() + "/R.raw.notificationsound");
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(1, notification);
}
Thanks.
From the documentation for ContentResolver:
The Uri should be one of the following formats:
android.resource://package_name/id_number
You are passing the String "R.raw.notificationsound" which means nothing.
Instead try this:
notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notificationsound );

Categories

Resources