android中的ringtone流程,Setting Ringtone in Android - Stack Overflow

@Maxood

The code from @Clive is what you need to set the ringtone. You will need the absolute path to the file, which you can't get from a raw resource.

The solution is to get the resource file asset and write it to the sdcard 1st, before you give it to the content resolver for insertion.

File newSoundFile = new File("/sdcard/media/ringtone", "myringtone.oog");

Uri mUri = Uri.parse("android.resource://com.your.package/R.raw.your_resource_id");

ContentResolver mCr = app.getContentResolver();

AssetFileDescriptor soundFile;

try {

soundFile= mCr.openAssetFileDescriptor(mUri, "r");

} catch (FileNotFoundException e) {

soundFile=null;

}

try {

byte[] readData = new byte[1024];

FileInputStream fis = soundFile.createInputStream();

FileOutputStream fos = new FileOutputStream(newSoundFile);

int i = fis.read(readData);

while (i != -1) {

fos.write(readData, 0, i);

i = fis.read(readData);

}

fos.close();

} catch (IOException io) {

}

Then you can use the previously posted solution

ContentValues values = new ContentValues();

values.put(MediaStore.MediaColumns.DATA, newSoundFile.getAbsolutePath());

values.put(MediaStore.MediaColumns.TITLE, "my ringtone");

values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/oog");

values.put(MediaStore.MediaColumns.SIZE, newSoundFile.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(newSoundFile.getAbsolutePath());

Uri newUri = mCr.insert(uri, values);

try {

RingtoneManager.setActualDefaultRingtoneUri(getContext(), RingtoneManager.TYPE_RINGTONE, newUri);

} catch (Throwable t) {

Log.d(TAG, "catch exception");

}

Don't forget to write the the permission

in your manifest

hope this helps

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值