How to check if resource pointed by Uri is available?

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

    There are few methods of DocumentProvider when applied to uri, return null if there is no document underlying uri. I chose getType(uri) which returns mime type of the document/file. If no document/file exists represented in uri, it returns null. Hence, to detect whether documennt/file exists or not, you can use this method like below.

    public static boolean exists(Context context, Uri uri)
    {
        return context.getContentResolver().getType(uri) !=null;
        
    }
    

    Other methods mentioned like querying the uri to get documentID or opening inputstream/outputstream did not work because they throw filenotfound exception if document/file does not exist, which resulted in crashing of app.

    You may attempt other methods which return null instead of throwing filenotfoundexception, if document/file does not exist.

提交回复
热议问题