检查URI是否来自可移动存储



如何检查从Action_open_document树中选择的URI用户是否是从可移动SD卡中获得的?我检查了一下,但是对于主SD卡和可移动的SD卡也一样!还有其他方法吗?

   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
     String id=DocumentsContract.getTreeDocumentId(uri);
                    Uri mainuri=DocumentsContract.buildDocumentUriUsingTree(uri,id);

                    grantUriPermission(G.context.getPackageName(), uri,   Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
          if(   "com.android.externalstorage.documents".equals(uri.getAuthority())){
// its return true for primary and removable sd card !!

}

no。

不需要以任何方式识别存储提供商的Uri。您的假设(对于某个存储提供商而言,权限为com.android.externalstorage.documents)在任何Android设备上都不必正确。设备制造商可以为自己的存储提供商提供自己的Uri结构。

由于Android Q,您必须使用SAF。为了知道URI是否是可移动的媒体,您可以尝试使用路径字符串:如果您在uri.getPath()中找到" hhhhhhhhh:"(其中H = H = Hexadecimal string字符),则意味着是可移动的媒体。

 /**
 * 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;
}

最后一种方法使用较少的内存。以下方法是由于正则弦字符串更快地消耗螺母,但速度较短,但速度更快:

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;
}

更新:原始的正则是SDCARD上的子文件夹的作品。要包括根目录,请删除最后一个" d"字符。这是正确的言论:

".*\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]]:.*"

,正确的功能将是:

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;
}

最新更新