我有Uri指出的资源(音乐文件).在尝试使用MediaPlayer播放之前,如何查看是否可用?
它的Uri存储在数据库中,所以当文件被删除或卸载的外部存储器时,我只是在调用MediaPlayer.prepare()时收到异常.
在上述情况下,我想播放系统默认的铃声.我当然可以做到这一点,我抓住以上例外,但也许有一些更优雅的解决方案?
编辑:
我忘了提到音乐文件Uri实际上是通过使用铃声优先购买的.这意味着我可以让Uri指向内部存储,外部存储或默认系统铃声的铃声.
Uri的例子是:
>内容://设置/系统/铃声 – 用于选择默认铃声
> content:// media / internal / audio / media / 60 – 用于内部存储上的铃声
> content:// media / external / audio / media / 192 – 用于外接存储器上的铃声
我很高兴提出“新的File(路径).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);
- 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
- }