我有 Uri 指向的资源(音乐文件)。在我尝试使用 MediaPlayer 播放之前如何检查它是否可用?
它的 Uri 存储在数据库中,因此当文件被删除或在未安装的外部存储上时,我只会在调用 MediaPlayer.prepare() 时出现异常。
在上述情况下,我想播放系统默认铃声。我当然可以在捕获到上述异常后这样做,但也许有一些更优雅的解决方案?
编辑: 我忘了说,Uri 的音乐文件实际上是通过使用 RingtonePreference 获取的。这意味着我可以让 Uri 指向内部存储、外部存储上的铃声或默认系统铃声。
Uri 的例子是:
- content://settings/system/ringtone - 用于选择默认铃声
- content://media/internal/audio/media/60 - 用于内部存储中的铃声
- content://media/external/audio/media/192 - 用于外部存储中的铃声
我对提议的“新 File(path).exists() 方法感到满意,因为它使我免于提到的异常,但一段时间后我注意到它对我所有的铃声选择都返回 false ... 还有其他想法吗?
最佳答案
建议的方法不起作用的原因是因为您使用的是 ContentProvider
URI 而不是实际的文件路径。要获取实际的文件路径,您必须使用光标来获取文件。
假设 String contentUri
等于内容 URI,例如 content://media/external/audio/media/192
ContentResolver cr = getContentResolver();
String[] projection = {MediaStore.MediaColumns.DATA}
Cursor cur = cr.query(Uri.parse(contentUri), projection, null, null, null);
if (cur != null) {
if (cur.moveToFirst()) {
String filePath = cur.getString(0);
if (new File(filePath).exists()) {
// do something if it exists
} else {
// File was not found
}
} else {
// Uri was ok but no entry found.
}
cur.close();
} else {
// content Uri was invalid or some other error occurred
}
我没有将此方法用于声音文件或内部存储,但它应该 有效。查询应将单行直接返回到您的文件。
关于android - 如何检查 Uri 指向的资源是否可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7645951/