Android(4.4) - Notification sound not playing - android

This is a very common question, but I did not find an answer to it. I created app with Xamarin.Android. My app creates a locale notifications (with time delayed), it works except android 4.4(on emulator and device).
My device: Samsung GT-I9195, Android 4,4,2
This is my code create notification (in BroadcastReceiver):
var builder = new NotificationCompat.Builder(context)
.SetContentTitle(notification.Title)
.SetContentText(notification.Body)
.SetSmallIcon(notification.IconId)
.SetAutoCancel(true);
builder.SetDefaults(NotificationCompat.DefaultAll);
In this case, only vibro works.
I tried other options, for example:
builder.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Alam));
...
//load embeded sound
Android.Net.Uri alarmUri = Android.Net.Uri.Parse($"{ ContentResolver.SchemeAndroidResource}:{CrossCurrentActivity.Current.AppContext.PackageName}/{Resource.Raw.sound}");
builder.SetSound(alarmUri);
I even tried to launch a media player(in OnReceive).
MediaPlayer mp = MediaPlayer.Create(CrossCurrentActivity.Current.AppContext, alarmUri);
mp.Start();
But all this does not work. Only vibration, without sound. Any ideas?

Related

Xamarin cross notification custom sound

I am using
Xamarin + firebase notification for cross platform app
Need
To change the default notification sound
Expect
The sound changed, even if the app is colse. Which means I will assign a different tone for the notifications which come to this app
Coding
No need to write any code to play the sound or to trigger the on notofication recieved event at all
Current result:
I success to do this with IOS only, but faild with Android.
Now I can recieve notification with custom sound even if the app is closed, without writting any code for this
My code
For IOS
1- add this line to the notification payload
"sound": "test.wav"
only sound name with the extention
2- add test.wav to IOS project under Resources as "BundleResource", or "Embedded Resource"
3- send the notification, and do not care about "NotificationRecieved" event at all
4- kill the app, and send the notification
5- notification recieved with custom sound "test.wav"
6- IOS accect "wav" or "caf" files only
For Android
Repeat the same with "wav" file, but with some changes like:
1- the sound file add at Resources/raw as AndroidResource For Project.Droid
2- try to change the payload to be:
"sound": "test.wav"
"sound": "test"
"sound": "raw/test.wav"
"sound": "raw/test"
But never success to play the sound
Question
I am sure there is something wrong in the ("sound": "test.wav") format.
I tested it with and without extention,
I do not need to handle the sound by coding, I want to assign the tone exactly as done with the IOS project
I expected IOS to be harder than Android! but at end it was easy
Any help, please?
Finally, I solved it.
For those who face the same problem I will post the solution.
For IOS, you can only pass the sound file name as I said before.
For Android, it is comples. I noticed that the app uses the default system sound for all notification which recieved in the background mode, closed, or killed app.
I went to the app settings, then I found a channel name "Miscellaneous" which used for such notifications.
The idea was how to change this channel sound?
If you create a channel with the same name, it will not work because you have to use channel name + channel ID.
I searched and finaly find the default channel id which is "fcm_fallback_notification_channel".
The second step was to create a channel with this name and id, in hope to override the system one.
I created this channel in the app start with the following code:
var importance = NotificationImportance.High;
var soundFileName = "sound";
NotificationChannel chan = new NotificationChannel("fcm_fallback_notification_channel", "Miscellaneous", importance);
chan.EnableVibration(true);
chan.LockscreenVisibility = NotificationVisibility.Public;
chan.SetSound(Android.Net.Uri.Parse("android.resource://com.myapp.test/raw/" + soundFileName), null);
NotificationManager notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(chan);
And it works as expected :)
Now I can recieve nottifications with the custom sound even if the app is closed, killed, or background mode.
I did not think that I can do this, finally.
Thanks for everyone.
Hope this can help someone.
For the Android, you should set the sound in NotificationChannel
var channel = new NotificationChannel(CHANNEL_ID, "FCM Notifications", NotificationImportance.Default)
{
Description = "Firebase Cloud Messages appear in this channel"
};
var audioattributes = new AudioAttributes.Builder();
audioattributes.SetContentType(AudioContentType.Music);
audioattributes.SetUsage(AudioUsageKind.Notification);
channel.SetSound(global::Android.Net.Uri.Parse("android.resource://" + this.ApplicationContext.PackageName + "/raw/app_sound"), audioattributes.Build());
Note: If you set it, please uninstall the app to alter sound settings, Check out these link for more details.

Change notification tune in notification channel settings

I'm following this guide to configure my NotificationChannels https://developer.android.com/training/notify-user/channels.html#java
But when I open the settings screen with this code:
Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
intent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
intent.putExtra(Settings.EXTRA_CHANNEL_ID, myNotificationChannel.getId());
startActivity(intent);
There is no tune preference. I can only turn On/Off the sound. Do I need some additional configuration of my channel, or is it impossible to set custom tune of notification?(I know that I can play the tune manually when notification pops up, but I really don't like this solution)
Channel code:
public String createChannel() {
NotificationChannel channel = new NotificationChannel(INCOMING_CHAT_CHANNEL_ID, INCOMING_CHAT_CHANNEL_TITLE,
NotificationManager.IMPORTANCE_HIGH);
channel.setDescription(INCOMING_CHAT_CHANNEL_DESCRIPTION);
getNotificationManager().createNotificationChannel(channel);
return channel.getId();
}
And then I use returned channel Id:
Notification sound setting will only appear for higher priority notifications.
Try to change your Channel behaviour to first (Make sound and pop up screen) or second (Make sound) option.
Please try to post the code where you are creating the Notification channel.

Setting notification sound volume

I am using a NotificationChannel to define my app's notification. I set it's sound with the following code :
AudioAttributes.Builder constructeurAttributsAudio=new AudioAttributes.Builder();
constructeurAttributsAudio.setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT);
canalNotification.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + contexte.getPackageName() + "/raw/cloche"),constructeurAttributsAudio.build());
When the notification appears, the sound is correctly emitted, but it's volume is set at the maximum and doesn't take into account the sound level set for notifications by the user. Does anyone know how I can have my app set the notification sound level to the value choosen by the user?
Edit #1 : if I copy the code to execute it in the app's body (triggered by a Button click) instead of in the onReceive method of my BroadcastReceiver, the notification sound is correctly emitted at the sound level chosen by the user for notifications.
Edit #2 : strangely, the notification sound level is correct when the app is executed on the emulator! Could the reason be a parameter in the phone's configuration? (They both run under Android 9).
Uninstalling and reinstalling the app solved the problem!
I use the following code, hopefully useful for you too:
private void setvolume(int volume)
{
AudioManager manager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
manager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);
Uri notification = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
MediaPlayer player = MediaPlayer.create(getApplicationContext(), notification);
player.start();
}

Notifications on android oreo - dynamically enable sound/vibration

I have a foreground service that shows a progress notification and if it is finished, the notification is reused as a normal notification to show the service's result
I allow the user to define inside my app if the final notification is silent or not. So here is what I do:
// 1) Create notifcation channel in my app, once only
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationChannel.enableLights(false);
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
// 2) Init notification
notificationBuilder = new NotificationCompat.Builder(this, notificationChannelId);
notificationBuilder.setAutoCancel(false);
notificationBuilder.setOngoing(true);
notificationBuilder.setTicker(ticker);
notificationBuilder.setContentText(title);
// 3) Updating the notification to show the services progress
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(subTitle);
// 4) preparing the final notification
if (!MainApp.getPrefs().silentNotifications()) {
if (globalError || updated > 0 || prepared > 0 || contactsWithError.size() > 0) {
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
notificationBuilder.setVibrate(new long[]{0, 500});
notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
} else {
notificationBuilder.setVibrate(new long[]{});
notificationBuilder.setSound(null);
}
}
Problems
an android oreo user told me, the notification is making a sound/vibrates on each update
the same user told me, after a restart, the sound/vibration is gone
What I want
I want that the notification channel vibrates and plays a sound by default (if the user did not change this in the android settings for my channel)
I want to dynamically decide that I don't play sounds/vibrate even if sound/vibration is enabled
If the user disables sound/vibration for my channel, I'm fine, than I won't play a sound nor vibrate at any time
How am I supposed to achieve that?
Edit - one solution is following:
Use two channels:
one for updating the notification
one for the final result notification.
This looks weird to me, I would assume that I can use one channel, set it up with sounds by default and use this channel. I should be able to define myself to play a sound or not, if the user allows me to play a sound (seems like I'm forced to play a sound currently). Otherwise I never play a sound of course. It looks like currently you need two channels for every service, that shows progress in the notification and plays a sound by default if finished. That's bad to explain to the user because you need two channels for the same action, on for the progress and one for the final result...
I was annoyed with the sound of my notifications. I did this.
.setSound(Uri.parse("android.resources://" + getPackageName() + "/" + R.raw.silence))
and this
.setOnlyAlertOnce(true)
Also note that you have to set them in the channel too.

How to send a notification with sound and vibration in do not disturb(DND) mode in android

How can I send a notification with sound and vibration when phone is in do not disturb mode on Android Devices.
I use the following code, and it is working when my application is currently in foreground.
PendingIntent contentIntent = PendingIntent.getActivity(this, NOTIFICATION_ID,
resultIntent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Notification")
.setStyle(new NotificationCompat.BigTextStyle().bigText("You've received new message."))
.setContentText("You've received new message.");
// FOR SILENT MODE
AudioManager am = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
// For Normal mode
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
am.setStreamVolume(AudioManager.STREAM_MUSIC, am.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
mBuilder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
// Set Vibrate, Sound and Light
int defaults = 0;
defaults = defaults | Notification.DEFAULT_LIGHTS;
// defaults = defaults | Notification.DEFAULT_VIBRATE;
// defaults = defaults | Notification.DEFAULT_SOUND;
mBuilder.setDefaults(defaults);
mBuilder.setSound(Uri.parse("android.resource://" + getPackageName()
+ "/" + R.raw.siren));
// Cancel the notification after its selection
mBuilder.setAutoCancel(true);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
I also want notifications with sound and vibration when my app is in background.
Generally speaking you can't. Even notification with MAX priority wont be shown in DND mode.
The possible workaround that I can imagine is to use android.permission.SYSTEM_ALERT_WINDOW to draw custom notification over system window (FB Messanger works in similar way) : Creating a system overlay window (always on top) .
But this method is suitable only in rare cases and most of the time it's a violation of Android UI/UX best practices.
Ok good news you are half way there.
I achieved this previously by using AudioManager & VIBRATOR_SERVICE (yea I know ;)
The idea is not to use NotificationCompat.Builder because it will rely on system settings and if device is in silent mode, it won't vibrate nor play sound. You have to manually play a sound using AudioManager & vibrate using VIBRATOR_SERVICE.
You are using AudioManager & setting the properties but you are never actually asking it to play the sound. So, in your code its never actually utilized.
Here's an example of how to play a sound using AudioManager, it will also ignore silent mode:
Here's an example of using VIBRATOR_SERVICE:
Combine these 2 approaches and ditch NotificationCompat.Builder
If you can get right permissions to change settings of device, then you could show notifications with sound and vibration at your apps. Also check this out.

Categories

Resources