How to check if resource pointed by Uri is available?

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

    For those still looking out for a solution [works perfectly fine as of Dec 2020] and behaves as expected for all edge cases, the solution is a follows:

    boolean bool = false;
            if(null != uri) {
                try {
                    InputStream inputStream = context.getContentResolver().openInputStream(uri);
                    inputStream.close();
                    bool = true;
                } catch (Exception e) {
                    Log.w(MY_TAG, "File corresponding to the uri does not exist " + uri.toString());
                }
            }
    

    If the file corresponding to the URI exists, then you will have an input stream object to work with, else an exception will be thrown.

    Do not forget to close the input stream if the file does exist.

    NOTE:

    DocumentFile sourceFile = DocumentFile.fromSingleUri(context, uri);
    boolean bool = sourceFile.exists();
    

    The above lines of code for DocumentFile, does handle most edge cases, but what I found out was that if a file is created programmatically and stored in some folder, the user then visits the folder and manually deletes the file (while the app is running), DocumentFile.fromSingleUri wrongly says that the file exists.

提交回复
热议问题