简体   繁体   中英

Android Studio: Set mp3 from raw folder as device ringtone in 2020

I'd like to set a raw mp3 file, which is located in my raw folder, as the device ringtone (using java). Unfortunately the old tutorials do not work anymore, often because you need some write permissions. I tried everything out there, but no solution works (the solutions are all veery old...).

Can anyone help me please? Has anyone a good code example for that problem?

If you dont mind putting your file in assets folder then you can do this:

  • copy your mp3 from assets to device accessible memory

  • set the new copied file as ringtone using

     void set_asset_ringtone(Context context, String output_file_path, String asset_name) throws IOException { ///////////////copying from assets to filepath//////////////// InputStream externalDbStream = context.getAssets().open(asset_name); String outFileName =output_file_path+"/"+asset_name; OutputStream localDbStream = new FileOutputStream(outFileName); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = externalDbStream.read(buffer)) > 0) { localDbStream.write(buffer, 0, bytesRead); } localDbStream.close(); externalDbStream.close(); //////Setting the ringtone ///////////////// File rigntone_file=new File(outFileName); ContentValues values = new ContentValues(); values.put(MediaStore.MediaColumns.DATA, rigntone_file.getAbsolutePath()); values.put(MediaStore.MediaColumns.TITLE, "ring"); values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3"); values.put(MediaStore.MediaColumns.SIZE, rigntone_file.length()); values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name); values.put(MediaStore.Audio.Media.IS_RINGTONE, true); values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true); values.put(MediaStore.Audio.Media.IS_ALARM, true); values.put(MediaStore.Audio.Media.IS_MUSIC, false); Uri uri = MediaStore.Audio.Media.getContentUriForPath(rigntone_file.getAbsolutePath()); Uri newUri = getContentResolver().insert(uri, values); try { RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri); } catch (Throwable t) { } }

You will need these permisions

<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

And maybe

<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

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