How to check if resource pointed by Uri is available?

前端 未结 6 2289
说谎
说谎 2021-02-07 00:44

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

Its Uri is stored in database, so when the file

6条回答
  •  遇见更好的自我
    2021-02-07 01:26

    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.

    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.

提交回复
热议问题