android设置手机铃声,通知,闹钟声音代码
时间: 2024-01-21 08:03:59 浏览: 174
以下是Android设置手机铃声、通知、闹钟声音的代码示例:
设置铃声:
```java
String filepath = "/sdcard/ringtone.mp3"; // 铃声文件路径
File file = new File(filepath);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
String title = file.getName();
values.put(MediaStore.MediaColumns.TITLE, title);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
Uri uri = MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath());
Uri newUri = getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri); // 设置铃声
```
设置通知声音:
```java
String filepath = "/sdcard/notification.mp3"; // 通知声音文件路径
File file = new File(filepath);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
String title = file.getName();
values.put(MediaStore.MediaColumns.TITLE, title);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
Uri uri = MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath());
Uri newUri = getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION, newUri); // 设置通知声音
```
设置闹钟声音:
```java
String filepath = "/sdcard/alarm.mp3"; // 闹钟声音文件路径
File file = new File(filepath);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
String title = file.getName();
values.put(MediaStore.MediaColumns.TITLE, title);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
Uri uri = MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath());
Uri newUri = getContentResolver().insert(uri, values);
AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000, PendingIntent.getBroadcast(context, 0, new Intent(RingtoneManager.ACTION_RINGTONE_PICKER), 0)); // 设置闹钟
```
注意:需要在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
```
阅读全文