How to check if resource pointed by Uri is available?

前端 未结 6 2282
说谎
说谎 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:34

    As of Kitkat you can, and you should, persist URIs that your app uses if necessary. As far as I know, there's a 128 URI limit you can persist per app, so it's up to you to maximize usage of those resources.

    Personally I wouldn't deal with direct paths in this case, but rather check if persisted URI still exists, since when resource (a file) is deleted from a device, your app loses rights to that URI therefore making that check as simple as the following:

    getContext().getContentResolver().getPersistedUriPermissions().forEach( {element -> element.uri == yourUri});
    

    Meanwhile you won't need to check for URI permissions when a device is below Kitkat API level.

    Usually, when reading files from URIs you're going to use ParcelFileDescriptor, thus it's going to throw if no file is available for that particular URI, therefore you should wrap it with try/catch block.

提交回复
热议问题