簡體   English   中英

檢查 uri 是否來自可移動存儲

[英]check if a uri is from removable storage

如何檢查從 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 !!


}

從android Q開始,你必須使用SAF。 為了知道 URI 是否是可移動媒體,您可以嘗試使用路徑字符串:如果您在 uri.getPath() 中找到類似“HHHH-HHHH:”(其中 H = 十六進制字符串字符)的字符串,則表示是可移動媒體。

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

沒有。

不要求以任何方式識別來自存儲提供者的Uri 您的假設(某個存儲提供商的權限是com.android.externalstorage.documents )在任何 Android 設備上都不一定正確。 設備制造商可以提供他們自己的存儲提供者,以及他們自己的Uri結構。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM