9.0SDCard文件訪問權限(二)

接上篇:https://blog.csdn.net/a396604593/article/details/87878425

上篇提到了9.0之後,SDCard的解決方案

背景描述:

但 documentFile.findFile(split[i]); findFile方法耗時巨長,此方法文件越多耗時越長。

大概1000個圖片文件,findfile需要花費5s以上。

那麼,我們刪除一個文件就需要漫長的等待過程。

File file4=new File(path);//這裏沒有權限刪除
DocumentFile mDocumentFile = DocumentFile.fromFile(file4);//這裏依然沒有權限刪除
Uri mSafUri = parseUri(mDocumentFile.getUri());//uri轉換,把uri轉換成有權限的uri(字符串拼接uri)
try {
    DocumentsContract.deleteDocument(activity.getContentResolver(), mSafUri);//通過uri刪除文件
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

以上,關鍵點在於通過uri拼接,替換掉了之前的findfile方法耗時,有效降低了刪除等待時間。

private Uri parseUri(Uri uri) {
        //content://com.android.externalstorage.documents/tree/418A-1D08%3Attt
        //content://com.android.externalstorage.documents/tree/418A-1D08%3AAndroid%2Fdata%2Fcom.amazon.mp3
        //file:///storage/418A-1D08/ttt
        if (uri == null) return null;
        if (uri.toString().startsWith("content")) return uri;
        //TODO: this method is temporary, just work ok if foldername has no blank or other special character.
        //For example "thisisafolder" is ok and "this is a folder" cant work
        String strUri = uri.toString();
        String outUri = strUri.substring(16);
        if (!outUri.contains("/")) {
            outUri = "content://com.android.externalstorage.documents/tree/" + outUri + "%3A/document/" + outUri + "%3A";
//            Log.i(TAG, "parseUri outUri" + PreferenceSdCard.getSDPreference(SafUtil.PreferenceSdCard.getCurrentSDUniqueID()));
        } else {
            int s = outUri.indexOf("/");
            String strStorage = outUri.substring(0, s);
            String strFile = outUri.substring(s + 1);
            if (strFile.contains("/")) {
                strFile = strFile.replace("/", "%2F");
            }
            //outUri = "content://com.android.externalstorage.documents/tree/418A-1D08%3A/document/" + strStorage + "%3A" + strFile;
            outUri = "content://com.android.externalstorage.documents/tree/" + strStorage + "%3A/document/" + strStorage + "%3A" + strFile;
            //return Uri.parse(outUri);
        }
        return Uri.parse(outUri);
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章