'How to simply set the default alarm tone to a custom tone
My app currently uses the default alarm ringtone for certain events, which is realized using the following two lines of code in onCreate()
:
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
ringtone = RingtoneManager.getRingtone(getApplicationContext(), notification);
At the start of the activity class, I have defined ringtone
:
Ringtone ringtone;
At the places in the code where the alarm should actually sound, I use ringtone.play()
and ringtone.stop()
. Works fine.
Now, I would now like to replace the default alarm tone with a custom tone (alarmsound.mp3
). To that purpose, I've placed that custom tone in the resources of the app (res/raw/alarmsound.mp3
).
How do I change my code to play the custom tone? I've checked this question for duplicates, but the answers (and even the questions) seem incredibly complicated and long (imagine accessing custom-made drawables
would require so much code). Is there an easy way to do this, like by modifying or adding to the above code (and without having to ask the user any extra permissions)?
I already tried
Uri notification = RingtoneManager.getActualDefaultRingtoneUri(MainActivity.this, R.raw.alarmsound);
ringtone = RingtoneManager.getRingtone(getApplicationContext(), notification);
but that gave a NullPointerException
in ringtone.play()
Solution 1:[1]
RingtoneManager.setActualDefaultRingtoneUri(baseContext, RingtoneManager.TYPE_RINGTONE, Uri.parse("android.resource://com.apppackage/" + R.raw.alarmsound));
RingtoneManager.getRingtone(baseContext, Uri.parse("android.resource://com.apppackage/" + R.raw.alarmsound));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Vini5458 |