Search code examples
androidstorage-access-framework

Check if a Document Uri is of External SD Card Root


How can we check whether the selected document using ACTION_OPEN_DOCUMENT_TREE is the external SD Card root or not?


Solution

  • Here're the functions I am using for determining if the Uri is of External SD Card and whether it's situated at the root of the SD card or not

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private static boolean checkIfSDCardRoot(Uri uri) {
        return isExternalStorageDocument(uri) && isRootUri(uri) && !isInternalStorage(uri);
    }
    
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private static boolean isRootUri(Uri uri) {
        String docId = DocumentsContract.getTreeDocumentId(uri);
        return docId.endsWith(":");
    }
    
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static boolean isInternalStorage(Uri uri) {
        return isExternalStorageDocument(uri) && DocumentsContract.getTreeDocumentId(uri).contains("primary");
    }
    
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }
    

    These methods are taken from the library I have created for dealing with the Storage Access Framework. The library is open-sourced and present on Github - NoobFileChooser. The functions are present in this file.