Android: Get default or currently set alarm sound/tone? - android

I searched with many terms and sentencing but could not find any information on this whatsoever.
So anyways: How can I get default or currently set music/tone/sound for Alarm (Default app) ?
Say if I wake up every morning with alarm song playing: Song#1 using default alarm app, how can I get that Song#1 in my custom app?
I am trying to create my own alarm app but I don't want to set a tone that user may not like.
Perhaps there is a way to open default alarm tone picker/browser and let user set it in my custom app? Or does all of that need to be custom coded?
If none of above is possible - How can I just get default alarm sound to play in my app?

Uri alarmTone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
Ringtone ringtoneAlarm = RingtoneManager.getRingtone(getApplicationContext(), alarmTone);
ringtoneAlarm.play();

Related

Android silent mode - is there a way for a notification to sound?

Context
I am working on an app that uses FCM. The use of this application is to alert a user of an event that is occurring (such as an alarm system). In view of the alarm nature of the notification, it is essential that a sound is played when receiving a notification even if the smartphone is in silent or vibrate mode.
Question
Is there a way to achieve this described behavior for all smartphone modes (silent, vibrate, sound) ?
What I've tried
As I am working with API26> I created a notification channel to have the highest priority which is Max Priority,
I've set the notification channel to bypass Do Not Disturb mode like so:
notificationChannel.SetBypassDnd(true);
Obviously it only affects the Do Not Disturb mode and absolutely not what I want,
In the notification builder, I've set the notification priority to Max and the category to Alarm:
.SetPriority(NotificationCompat.PriorityMax)
.SetCategory(NotificationCompat.CategoryAlarm);
Reading the Android documentation, this feature is also related to Do Not Disturb Mode.
I am actively looking for a solution to this problem, but at this point I'm a bit stuck.
Any suggestions ?
I've read about a full screen intent in the Android documentation but it's not written that a sound will fire if the smartphone is in silent mode.
Maybe there is a way to create a service that rings when the notification arrives? But this service has to be running all the time, which isn't really a good design idea.
If you guys have any idea, any remarks or suggestions, i'd be grateful to read them !
I believe you need to set priority for your notification.
private fun setPriorityForAlarmNotification() {
if (notificationManager.isNotificationPolicyAccessGranted) {
notificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_PRIORITY)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val policy = NotificationManager.Policy(PRIORITY_CATEGORY_ALARMS, 0, 0)
notificationManager.notificationPolicy = policy
}
}
}
As I can see you setCategory for your notification builder is NotificationCompat.CategoryAlarm.
However, in order to set this priority, you need this permission on your manifest
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
And request permission if needed
fun requestNotificationPolicyPermission() {
val notificationManager = activity!!.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
if (!notificationManager.isNotificationPolicyAccessGranted) {
val intent = Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS)
startActivityForResult(intent, REQUEST_CODE_NOTIFICATION_POLICY)
}
}
This solution should work absolutely. Hope this can help you :D

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.

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

Android Marshmallow sound only Notification?

In Lollipop and below, you could easily send a sound only notification by omitting the icon, content title and content text when constructing, like so:
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());
builder.setSound(Uri.parse(ringtone));
notificationManager.notify(9998, builder.build());
In Marshmallow, I'm forced to include at least an icon, or I get a 'no valid small icon' exception. I want to use the Notification system, but don't always want to display a notification in the notification bar. Is this possible with Marshmallow, or should I change to playing my notification sound with media player, even though sometimes I, or the user, may want to display a notification?
I read somewhere that the docs said icon was required even thought it didn't throw an exception when omitted in Lollipop and below. After looking into using MediaPlayer, I finally decided to use RintoneManager to play it. I am using the notification sounds, so may as well save myself some typing and do a quick
try {
RingtoneManager.getRingtone(getApplicationContext(), Uri.parse(ringtone)).play();
} catch (Exception e) {
e.printStackTrace();
}
to trigger the sound, I'll save the notification for when I need an actual notification. I was already planing on using if, depending on whether or not the notification should appear in the notification bar.

Android notification sound not playing, intermittently

I have searched for this, so apologies if this has been answered already (I am happy to be redirected), but specifically our issue is intermittent.
Our clients are complaining that the notification audio is, intermittently, not 'chiming' when an event is sent to their phones from our software. It will work fine for a time, then 'just stop for a few hours' (extrapolating from the complaints of our customers).
We've not been able to reproduce this in house, but the frustration we are getting from our customers is such that we really need to fix it.
Our customers insist they are not making phone calls, playing audio or running other software, and from seeing their phones, I largely believe them.
We have noticed this largely on Jellybean, as this is what most of our clients are running, however it may not be isolated to this case.
Am I doing something wrong, or is there a better way to 'chime' for a notification. At this stage I am happy to try something different
void updateNotification()
{
Notification.Builder builder = new Notification.Builder(_context);
// Set the appearance of the notification:
int icon;
String title;
String description;
// ...
//CODE setting icon, title and description
// ...
builder.setSmallIcon(icon);
builder.setContentTitle(title);
builder.setContentText(description);
builder.setTicker(description);
// Set the sound for the notification:
builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM));
Intent intent = new Intent(_context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(MainActivity.EXTRA_TAB, MainActivity.EXTRA_TAB_TASKS);
builder.setContentIntent(PendingIntent.getActivity(_context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
// Update the notification:
NotificationManager manager = (NotificationManager)_context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(_notificationId, builder.build());
}
For some reason, I noticed some devices mute all volumes (including the alarm volume) when they are put on silent or vibrate mode. And in those modes, for these devices, this volume can't be changed unless you change the mode.
I had users complaining of a similar problem and had to handle it by forcing a change of mode to ensure the volume is high enough. I then played the audio and switched the mode back to the original configuration.
Edit: Here is a post from a user complaining about this. Notice on the screenshot there that the volume button for "alarms" is disabled on mute.
Edit 2: In my particular case, I run the following check to see if I need to increase the volume:
if (audioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL
&& audioManager.getStreamVolume(AudioManager.STREAM_ALARM) == 0) {
// Save current state and increase the volume
}
Whilst the answer #Ricardo gave is certainly worth including in your code, and I have left it in ours, my problem was largely due to the phone's power-management (this may have been obvious, but I'm newish to Android development).
Our notifications are required to be delivered when sent, and our user's phones were going into sleep mode, so we added a WakeLock (though, caring for their battery life, we only have it 'on' when the user was 'Signed In' to our app. At the end of their shift, the WakeLock was released).

Categories

Resources