Since android Q, you must use SAF. In order to know if a URI is a removable media, you can try using the path string: if you find a string like "HHHH-HHHH:" (where H = hexadecimal string character) in the uri.getPath() it means that is a removable media.
/**
* Check if SAF uri point to a removable media
* Search for this regular expression:
* ".*\\b[ABCDFE[0-9]][ABCDFE[0-9]][ABCDFE[0-9]][ABCDFE[0-9]]-[ABCDFE[0-9]][ABCDFE[0-9]][ABCDFE[0-9]][ABCDFE[0-9]]:\\b.*"
* @param uri: SAF URI
* @return true if removable, false if is internal
*/
public boolean isRemovable (Uri uri) {
String path = uri.getPath();
String r1 = "[ABCDEF[0-9]]";
String r2 = r1 + r1 + r1 + r1;
String regex = ".*\\b" + r2 + "-" + r2 + ":\\b.*";
if (path != null) {
return path.matches(regex);
} else return false;
}
The last method use less memory. The following method is faster nut consume more memory due the regex string, but is short and faster:
public boolean isRemovable (Uri uri) {
String path = uri.getPath();
if (path != null) {
return path.matches(".*\\b[ABCDFE[0-9]][ABCDFE[0-9]][ABCDFE[0-9]][ABCDFE[0-9]]-[ABCDFE[0-9]][ABCDFE[0-9]][ABCDFE[0-9]][ABCDFE[0-9]]:\\b.*");
} else return false;
}
UPDATE:
The original regex only works for subfolder on the SDCARD. To include the root directory, delete the last '\d' characters. This is the correct REGEX:
".*\\b[ABCDFE[0-9]][ABCDFE[0-9]][ABCDFE[0-9]][ABCDFE[0-9]]-[ABCDFE[0-9]][ABCDFE[0-9]][ABCDFE[0-9]][ABCDFE[0-9]]:.*"
so the correct function would be:
private boolean isRemovable (Uri uri) {
String path = uri.getPath();
String r1 = "[ABCDEF[0-9]]";
String r2 = r1 + r1 + r1 + r1;
String regex = ".*\\b" + r2 + "-" + r2 + ":.*";
if (path != null) {
return path.matches(regex);
} else return false;
}