之前项目里写的设置来电铃声和分享音频文件如下:
//设置来电铃声
public void setAsRingTone(String path) {
Log.d(TAG, "setAsRingTone--path:" + path);
File file = new File(path);
if (file.exists()) {
Uri newUri = null;
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, file.getName());
values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
//查询媒体数据库中存不存在对应文件路径的数据
Cursor cursor = this.getContentResolver().query(uri, null,
MediaStore.MediaColumns.DATA + "=?",
new String[] {
file.getAbsolutePath()
}, null);
try {
//如果存在则跟新媒体数据库,否则插入媒体数据库
if (cursor.moveToFirst() && cursor.getCount() > 0) {
String _id = cursor.getString(0);
getContentResolver().update(uri, values, MediaStore.MediaColumns.DATA + "=?",
new String[] {
file.getAbsolutePath()
});
newUri = ContentUris.withAppendedId(uri, Long.valueOf(_id));
} else {
newUri = this.getContentResolver().insert(uri, values);
}
Log.i(TAG, "newUri=" + newUri);
RingtoneManager.setActualDefaultRingtoneUri(this,
RingtoneManager.TYPE_RINGTONE, newUri);
Toast.makeText( getApplicationContext (),"铃声设置成功!",
Toast.LENGTH_SHORT ).show();
} catch (Exception e) {
// TODO: handle exception
Log.e(TAG, "Exception:" + e.toString());
} finally {
if (cursor != null) {
cursor.close();
}
}
} else {
Toast.makeText( getApplicationContext (),"文件不存在,铃声设置失败!",
Toast.LENGTH_SHORT ).show();
}
}
//分享音频文件
public void share(String path) {
Log.d(TAG, "Share--path:" + path);
File file = new File(path);
if (file.exists()) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("audio/*");
Uri uri = Uri.parse("file://" + path);
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "分享"));
} else {
Toast.makeText( getApplicationContext (),"文件不存在,分享失败!",
Toast.LENGTH_SHORT ).show();
}
}
当然,分享类型还有很多如:分享文字、图片等等,这里推荐一篇文章写的很详细了: