网上查了很多例子,都有点问题,综合几个自己写了个可以设置铃声、通知声音、闹钟声音和所有声音功能的方法。
首先写一个常量类(定义想要设置为那种铃声的标示):
AppConstant.javapublic interface AppConstant { public static final int RINGTONE = 0; //铃声 public static final int NOTIFICATION = 1; //通知音 public static final int ALARM = 2; //闹钟 public static final int ALL = 3; //所有声音}
?
此方法需要传入想要设置为铃声的全路径(如:/mnt/sdcard/mp3/a.mp3 ),和想要设置为那种铃声的标示:
private void setVoice(String path2,int id) { ContentValues cv = new ContentValues(); Uri newUri = null; Uri uri = MediaStore.Audio.Media.getContentUriForPath(path2); // 查询音乐文件在媒体库是否存在 Cursor cursor = this.getContentResolver().query(uri, null, MediaStore.MediaColumns.DATA + "=?", new String[] { path2 },null); if (cursor.moveToFirst() && cursor.getCount() > 0) { String _id = cursor.getString(0); switch (id) { case AppConstant.RINGTONE: cv.put(MediaStore.Audio.Media.IS_RINGTONE, true); cv.put(MediaStore.Audio.Media.IS_NOTIFICATION, false); cv.put(MediaStore.Audio.Media.IS_ALARM, false); cv.put(MediaStore.Audio.Media.IS_MUSIC, false); break; case AppConstant.NOTIFICATION: cv.put(MediaStore.Audio.Media.IS_RINGTONE, false); cv.put(MediaStore.Audio.Media.IS_NOTIFICATION, true); cv.put(MediaStore.Audio.Media.IS_ALARM, false); cv.put(MediaStore.Audio.Media.IS_MUSIC, false); break; case AppConstant.ALARM: cv.put(MediaStore.Audio.Media.IS_RINGTONE, false); cv.put(MediaStore.Audio.Media.IS_NOTIFICATION, false); cv.put(MediaStore.Audio.Media.IS_ALARM, true); cv.put(MediaStore.Audio.Media.IS_MUSIC, false); break; case AppConstant.ALL: cv.put(MediaStore.Audio.Media.IS_RINGTONE, true); cv.put(MediaStore.Audio.Media.IS_NOTIFICATION, true); cv.put(MediaStore.Audio.Media.IS_ALARM, true); cv.put(MediaStore.Audio.Media.IS_MUSIC, false); break; default: break; } // 把需要设为铃声的歌曲更新铃声库 getContentResolver().update(uri, cv, MediaStore.MediaColumns.DATA + "=?",new String[] { path2 }); newUri = ContentUris.withAppendedId(uri, Long.valueOf(_id)); // 一下为关键代码: switch (id) { case AppConstant.RINGTONE: RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE, newUri); break; case AppConstant.NOTIFICATION: RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION, newUri); break; case AppConstant.ALARM: RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM, newUri); break; case AppConstant.ALL: RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALL, newUri); break; default: break; } //播放铃声// Ringtone rt = RingtoneManager.getRingtone(this, newUri);// rt.play(); } }?
?
1 楼 mxjma 2012-01-13
在模拟器上通过 在手机上测试没反映