如何通过我的活动在 Android 中设置铃声?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1271777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set ringtone in Android from my activity?
提问by Vidar Vestnes
I'm trying to find a way to set a new default ringtone by code from my Android activity.
我试图找到一种方法来通过我的 Android 活动中的代码设置新的默认铃声。
I have already downloaded the ringtone into a bytearray
.
我已经将铃声下载到bytearray
.
回答by Vidar Vestnes
Finally, I managed to set the default ringtone to one that i downloaded. The download code is not included below, only what was needed to set it as default ringtone.
最后,我设法将默认铃声设置为我下载的铃声。下面不包含下载代码,只包含将其设置为默认铃声所需的代码。
File k = new File(path, "mysong.mp3"); // path is a file to /sdcard/media/ringtone
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "My Song title");
values.put(MediaStore.MediaColumns.SIZE, 215454);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.ARTIST, "Madonna");
values.put(MediaStore.Audio.Media.DURATION, 230);
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);
//Insert it into the database
Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());
Uri newUri = this.getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(
myActivity,
RingtoneManager.TYPE_RINGTONE,
newUri
);
Anyway, I do not totally understand what this code is doing.
无论如何,我不完全理解这段代码在做什么。
The Ringtone manager needs a uri to the file that is to be set as new ringtone. But this uri can not be directly to the sdcard like "/sdcard/media/ringtones/mysong.mp3". That does not work!
铃声管理器需要要设置为新铃声的文件的 uri。但是这个uri不能像“/sdcard/media/ringtones/mysong.mp3”那样直接到sdcard。那行不通!
What you need is the external file uri of the file which could be something like "/external/audio/media/46"
您需要的是文件的外部文件 uri,它可能类似于“/external/audio/media/46”
The 46 is the id of the column in the MediaStore database, so thats why you need to add the sdcard file into the database first.
46 是 MediaStore 数据库中列的 id,所以这就是您需要先将 sdcard 文件添加到数据库中的原因。
Anyway, how does mediastore maintain its ids? This number can get really high, as you do this operation many times.
无论如何,mediastore 是如何维护其 id 的?当您多次执行此操作时,此数字可能会变得非常高。
Do i need to delete this row my self? Problem is that some times i dont even controll the deleting of the file since it can be deleted directly from the sdcard with a filebrowser.
我需要自己删除这一行吗?问题是有时我什至无法控制文件的删除,因为可以使用文件浏览器直接从 SD 卡中删除它。
回答by russoue
回答by Kishan Kumar
Answer By Vidar is too long and it adds duplicate entries every time you want to set a song as ringtone . Instead you should try this
回答 Vidar 太长,每次您想将歌曲设置为铃声时,它都会添加重复的条目。相反,你应该试试这个
Uri newUri=Uri.parse("content://media/external/audio/media/"+ID);
try {
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);
}
catch (Throwable t) {
}
回答by SANJAY GUPTA
public void setRingtone() {
String ringtoneuri = Environment.getExternalStorageDirectory().getAbsolutePath() + "/media/ringtone";
File file1 = new File(ringtoneuri);
file1.mkdirs();
File newSoundFile = new File(ringtoneuri, "myringtone.mp3");
Uri mUri = Uri.parse("android.resource://globalapps.funnyringtones/raw/sound_two.mp3");
ContentResolver mCr = this.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) {
}
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/mp3");
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 {
Uri rUri = RingtoneManager.getValidRingtoneUri(this);
if (rUri != null)
ringtoneManager.setStopPreviousRingtone(true);
RingtoneManager.setActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_RINGTONE, newUri);
Toast.makeText(this, "New Rigntone set", Toast.LENGTH_SHORT).show();
} catch (Throwable t) {
Log.e("sanjay in catch", "catch exception"+e.getMessage());
}
}
回答by dondondon
This is the code i used! i hope it helps..
This is also the link.
这是我使用的代码!我希望它有帮助..
这也是链接。
String exStoragePath = Environment.getExternalStorageDirectory().getAbsolutePath();
String path=(exStoragePath +"/media/alarms/");
saveas(RingtoneManager.TYPE_RINGTONE);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+path+filename+".mp3"
+ Environment.getExternalStorageDirectory())));
File k = new File(path, filename);
ContentValues values = new ContentValues(4);
long current = System.currentTimeMillis();
values.put(MediaStore.MediaColumns.DATA, path + filename );
values.put(MediaStore.MediaColumns.TITLE, filename );
values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/3gpp");
//new
values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
// Insert it into the database
this.getContentResolver()
.insert(MediaStore.Audio.Media.getContentUriForPath(k
.getAbsolutePath()), values);
HAPPY CODING!
快乐编码!
回答by Gianluca Massera
I cannot comment the solution because I don't have enough reputation on stack overflow ... I want just add a way to add the audio file into media database without accessing directly to the database and hence avoiding to get duplicates. The solution is based on MediaScannerConnection, this is the code I used:
我无法评论该解决方案,因为我在堆栈溢出方面没有足够的声誉......我只想添加一种将音频文件添加到媒体数据库的方法,而无需直接访问数据库,从而避免获得重复项。该解决方案基于MediaScannerConnection,这是我使用的代码:
String[] files = { audioFullPath };
MediaScannerConnection.scanFile(
getApplicationContext(),
files,
null,
new OnScanCompletedListener() {
@Override
public void onScanCompleted(String path, Uri uri) {
Log.v("myapp", "file " + path + " was scanned seccessfully: " + uri);
}
}
);
回答by Tatson Baptista
provide intent for ringtone selection.
提供铃声选择的意图。
final Uri currentTone= RingtoneManager.getActualDefaultRingtoneUri(MainActivity.this, RingtoneManager.TYPE_ALARM);
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_RINGTONE);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Select Tone");
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, currentTone);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
startActivityForResult(intent, 999);
then catch the result of selection in onActivityResult
.
然后在onActivityResult
.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 999 && resultCode == RESULT_OK){
Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
txtView.setText("From :" + uri.getPath());
//Set selected ringtone here.
RingtoneManager.setActualDefaultRingtoneUri(
this,
RingtoneManager.TYPE_RINGTONE,
uri
);
}
}
回答by Mujahid khan
I have try these code its help
我已经尝试过这些代码的帮助
private void setRingtone(Context context, String path) {
if (path == null) {
return;
}
File file = new File(path);
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
String filterName = path.substring(path.lastIndexOf("/") + 1);
contentValues.put(MediaStore.MediaColumns.TITLE, filterName);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
contentValues.put(MediaStore.MediaColumns.SIZE, file.length());
contentValues.put(MediaStore.Audio.Media.IS_RINGTONE, true);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(path);
Cursor cursor = context.getContentResolver().query(uri, null, MediaStore.MediaColumns.DATA + "=?", new String[]{path}, null);
if (cursor != null && cursor.moveToFirst() && cursor.getCount() > 0) {
String id = cursor.getString(0);
contentValues.put(MediaStore.Audio.Media.IS_RINGTONE, true);
context.getContentResolver().update(uri, contentValues, MediaStore.MediaColumns.DATA + "=?", new String[]{path});
Uri newuri = ContentUris.withAppendedId(uri, Long.valueOf(id));
try {
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newuri);
Toast.makeText(context, "Set as Ringtone Successfully.", Toast.LENGTH_SHORT).show();
} catch (Throwable t) {
t.printStackTrace();
}
cursor.close();
}
}
回答by Andres Yajamin
I found this code from the Media application from Android.
我从 Android 的媒体应用程序中找到了这段代码。
Settings.System.putString(resolver,
Settings.System.RINGTONE, ringUri.toString());
this works form my.
这作品形式我的。