简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM