9.0SDCard文件访问权限(二)

接上篇:Android 9.0 sdCard文件读写_纵容_伊人倩影的博客-CSDN博客

上篇提到了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);
    }

你可能感兴趣的:(sdcard权限,android)