如何检查Uri指向的资源是否可用? [英] How to check if resource pointed by Uri is available?

查看:51
本文介绍了如何检查Uri指向的资源是否可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Uri指向的资源(音乐文件).在尝试使用MediaPlayer播放之前,如何检查它是否可用?

I have resource (music file) pointed by Uri. How can I check if it is available before I try to play it with MediaPlayer?

它的Uri存储在数据库中,因此,当删除文件或将其卸载到外部存储上时,当我调用MediaPlayer.prepare()时,只会得到异常.

Its Uri is stored in database, so when the file is deleted or on external storage that is unmounted, then I just get exception when I call MediaPlayer.prepare().

在上述情况下,我想播放系统默认的铃声.在遇到异常之后,我当然可以这样做,但是也许有一些更优雅的解决方案?

In above situation I would like to play systems default ringtone. I could of course do that after I catch above exception, but maybe there is some more elegant solution?

我忘了提到音乐文件Uri的确是通过使用RingtonePreference来获取的.这意味着我可以让Uri指向内部存储",外部存储"上的铃声或默认系统的铃声.

edit: I forgot to mention that music files Uri's are actually acquired by using RingtonePreference. This means that I can get Uri pointing to ringtone on Internal Storage, External Storage or to default systems ringtone.

乌里(Uri)的例子是:

Uri's examples are:

  • content://settings/system/ringtone-用于选择默认铃声
  • content://media/internal/audio/media/60-用于内部存储中的铃声
  • content://media/external/audio/media/192-用于外部存储上的铃声

我对提出的新File(path).exists()方法感到满意,因为它使我免于所提到的异常,但是一段时间后,我注意到它对我所有的铃声选择都返回false".还有其他想法吗?

I was happy with proposed "new File(path).exists() method, as it saved me from mentioned exception, but after some time I noticed that it returns false for all of my ringtone choices... Any other ideas?

推荐答案

建议的方法不起作用的原因是因为您使用的是 ContentProvider URI,而不是实际的文件路径.要获取实际的文件路径,必须使用光标来获取文件.

The reason the proposed method doesn't work is because you're using the ContentProvider URI rather than the actual file path. To get the actual file path, you have to use a cursor to get the file.

假设 String contentUri 等于内容URI,例如 content://media/external/audio/media/192

Assuming String contentUri is equal to the content URI such as 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 
}

我没有在声音文件或内部存储中使用此方法,但是应该有效.该查询应直接向您的文件返回一行.

I haven't used this method with sound files or internal storage, but it should work. The query should return a single row directly to your file.

这篇关于如何检查Uri指向的资源是否可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆