欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android使用DocumentFile读写外置存储的问题

程序员文章站 2021-12-08 11:54:40
最近在维护项目,app遇到安装在高版本的android时,以往直接授权和new file(path)的形式不再支持,日志也是说permission denied。。。。。好吧,换为documentfi...

最近在维护项目,app遇到安装在高版本的android时,以往直接授权和new file(path)的形式不再支持,日志也是说permission denied。。。。。好吧,换为documentfile。

经过一番操作,也终于实再对存储目录的读和写了,下面记录一下:

首先建一个documentfile的utils类:

import android.annotation.targetapi;
import android.content.context;
import android.content.sharedpreferences;
import android.net.uri;
import android.os.build;
import android.os.parcelfiledescriptor;
import android.preference.preferencemanager;
import android.provider.documentscontract;
import android.util.log;
 
import androidx.documentfile.provider.documentfile;
 
import java.io.file;
import java.io.filedescriptor;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import java.io.randomaccessfile;
import java.util.arraylist;
import java.util.list;
 
 
public class documentsutils {
 
    private static final string tag = documentsutils.class.getsimplename();
 
    public static final int open_document_tree_code = 8000;
 
    private static list<string> sextsdcardpaths = new arraylist<>();
 
    private documentsutils() {
 
    }
 
    public static void cleancache() {
        sextsdcardpaths.clear();
    }
 
    /**
     * get a list of external sd card paths. (kitkat or higher.)
     *
     * @return a list of external sd card paths.
     */
    @targetapi(build.version_codes.kitkat)
    private static string[] getextsdcardpaths(context context) {
        if (sextsdcardpaths.size() > 0) {
            return sextsdcardpaths.toarray(new string[0]);
        }
        for (file file : context.getexternalfilesdirs("external")) {
            if (file != null && !file.equals(context.getexternalfilesdir("external"))) {
                int index = file.getabsolutepath().lastindexof("/android/data");
                if (index < 0) {
                    log.w(tag, "unexpected external file dir: " + file.getabsolutepath());
                } else {
                    string path = file.getabsolutepath().substring(0, index);
                    try {
                        path = new file(path).getcanonicalpath();
                    } catch (ioexception e) {
                        // keep non-canonical path.
                    }
                    sextsdcardpaths.add(path);
                }
            }
        }
        if (sextsdcardpaths.isempty()) sextsdcardpaths.add("/storage/sdcard1");
        return sextsdcardpaths.toarray(new string[0]);
    }
 
    /**
     * determine the main folder of the external sd card containing the given file.
     *
     * @param file the file.
     * @return the main folder of the external sd card containing this file, if the file is on an sd
     * card. otherwise,
     * null is returned.
     */
    @targetapi(build.version_codes.kitkat)
    private static string getextsdcardfolder(final file file, context context) {
        string[] extsdpaths = getextsdcardpaths(context);
        try {
            for (int i = 0; i < extsdpaths.length; i++) {
                if (file.getcanonicalpath().startswith(extsdpaths[i])) {
                    return extsdpaths[i];
                }
            }
        } catch (ioexception e) {
            return null;
        }
        return null;
    }
 
    /**
     * determine if a file is on external sd card. (kitkat or higher.)
     *
     * @param file the file.
     * @return true if on external sd card.
     */
    @targetapi(build.version_codes.kitkat)
    public static boolean isonextsdcard(final file file, context c) {
        return getextsdcardfolder(file, c) != null;
    }
 
    /**
     * get a documentfile corresponding to the given file (for writing on extsdcard on android 5).
     * if the file is not
     * existing, it is created.
     *
     * @param file        the file.
     * @param isdirectory flag indicating if the file should be a directory.
     * @return the documentfile
     */
    public static documentfile getdocumentfile(final file file, final boolean isdirectory,
                                               context context) {
 
        if (build.version.sdk_int <= build.version_codes.kitkat) {
            return documentfile.fromfile(file);
        }
 
        string basefolder = getextsdcardfolder(file, context);
    //    log.i(tag,"lum_ basefolder " + basefolder);
        boolean originaldirectory = false;
        if (basefolder == null) {
            return null;
        }
 
        string relativepath = null;
        try {
            string fullpath = file.getcanonicalpath();
            if (!basefolder.equals(fullpath)) {
                relativepath = fullpath.substring(basefolder.length() + 1);
            } else {
                originaldirectory = true;
            }
        } catch (ioexception e) {
            return null;
        } catch (exception f) {
            originaldirectory = true;
            //continue
        }
        string as = preferencemanager.getdefaultsharedpreferences(context).getstring(basefolder,
                null);
 
        uri treeuri = null;
        if (as != null) treeuri = uri.parse(as);
        if (treeuri == null) {
            return null;
        }
 
        // start with root of sd card and then parse through document tree.
        documentfile document = documentfile.fromtreeuri(context, treeuri);
        if (originaldirectory) return document;
        string[] parts = relativepath.split("/");
        for (int i = 0; i < parts.length; i++) {
            documentfile nextdocument = document.findfile(parts[i]);
 
            if (nextdocument == null) {
                if ((i < parts.length - 1) || isdirectory) {
                    nextdocument = document.createdirectory(parts[i]);
                } else {
                    nextdocument = document.createfile("image", parts[i]);
                }
            }
            document = nextdocument;
        }
 
        return document;
    }
 
    public static boolean mkdirs(context context, file dir) {
        boolean res = dir.mkdirs();
        if (!res) {
            if (documentsutils.isonextsdcard(dir, context)) {
                documentfile documentfile = documentsutils.getdocumentfile(dir, true, context);
                res = documentfile != null && documentfile.canwrite();
            }
        }
        return res;
    }
 
    public static boolean delete(context context, file file) {
        boolean ret = file.delete();
 
        if (!ret && documentsutils.isonextsdcard(file, context)) {
            documentfile f = documentsutils.getdocumentfile(file, false, context);
            if (f != null) {
                ret = f.delete();
            }
        }
        return ret;
    }
 
    public static boolean canwrite(file file) {
        boolean res = file.exists() && file.canwrite();
 
        if (!res && !file.exists()) {
            try {
                if (!file.isdirectory()) {
                    res = file.createnewfile() && file.delete();
                } else {
                    res = file.mkdirs() && file.delete();
                }
            } catch (ioexception e) {
                e.printstacktrace();
            }
        }
        return res;
    }
 
    public static boolean canwrite(context context, file file) {
        boolean res = canwrite(file);
 
        if (!res && documentsutils.isonextsdcard(file, context)) {
            documentfile documentfile = documentsutils.getdocumentfile(file, true, context);
            res = documentfile != null && documentfile.canwrite();
        }
        return res;
    }
 
    /**
     * 重命名
     * @param context
     * @param src
     * @param dest
     * @return
     */
    public static boolean renameto(context context, file src, file dest) {
        boolean res = src.renameto(dest);
 
        if (!res && isonextsdcard(dest, context)) {
            documentfile srcdoc;
            if (isonextsdcard(src, context)) {
                srcdoc = getdocumentfile(src, false, context);
            } else {
                srcdoc = documentfile.fromfile(src);
            }
            documentfile destdoc = getdocumentfile(dest.getparentfile(), true, context);
            if (srcdoc != null && destdoc != null) {
                try {
                    log.i("renameto", "src.getparent():" + src.getparent() + ",dest.getparent():" + dest.getparent());
                    if (src.getparent().equals(dest.getparent())) {//同一目录
                        res = srcdoc.renameto(dest.getname());
                    } else if (build.version.sdk_int >= build.version_codes.n) {//不同一目录
                        uri renamesrcuri = documentscontract.renamedocument(context.getcontentresolver(),//先重命名
                                srcdoc.geturi(), dest.getname());
                        res = documentscontract.movedocument(context.getcontentresolver(),//再移动
                                renamesrcuri,
                                srcdoc.getparentfile().geturi(),
                                destdoc.geturi()) != null;
                    }
                } catch (exception e) {
                    e.printstacktrace();
                }
            }
        }
 
        return res;
    }
 
    public static inputstream getinputstream(context context, file destfile) {
        inputstream in = null;
        try {
            if (!canwrite(destfile) && isonextsdcard(destfile, context)) {
                documentfile file = documentsutils.getdocumentfile(destfile, false, context);
                if (file != null && file.canwrite()) {
                    in = context.getcontentresolver().openinputstream(file.geturi());
                }
            } else {
                in = new fileinputstream(destfile);
 
            }
        } catch (filenotfoundexception e) {
            e.printstacktrace();
        }
        return in;
    }
 
    public static outputstream getoutputstream(context context, file destfile) {
        outputstream out = null;
        try {
            if (!canwrite(destfile) && isonextsdcard(destfile, context)) {
                documentfile file = documentsutils.getdocumentfile(destfile, false, context);
                if (file != null && file.canwrite()) {
                    out = context.getcontentresolver().openoutputstream(file.geturi());
                }
            } else {
                out = new fileoutputstream(destfile);
 
            }
        } catch (filenotfoundexception e) {
            e.printstacktrace();
        }
        return out;
    }
 
    /**
     * 获取文件流
     * @param context
     * @param destfile 目标文件
     * @param mode may be "w", "wa", "rw", or "rwt".
     * @return
     */
    public static outputstream getoutputstream(context context, file destfile, string mode) {
        outputstream out = null;
        try {
            if (!canwrite(destfile) && isonextsdcard(destfile, context)) {
                documentfile file = documentsutils.getdocumentfile(destfile, false, context);
                if (file != null && file.canwrite()) {
                    out = context.getcontentresolver().openoutputstream(file.geturi(), mode);
                }
            } else {
                out = new fileoutputstream(destfile, mode.equals("rw") || mode.equals("wa"));
 
            }
        } catch (filenotfoundexception e) {
            e.printstacktrace();
        }
        return out;
    }
 
    public static filedescriptor getfiledescriptor(context context, file destfile) {
        filedescriptor fd = null;
        try {
            if (/*!canwrite(destfile) && */isonextsdcard(destfile, context)) {
                documentfile file = documentsutils.getdocumentfile(destfile, false, context);
                if (file != null && file.canwrite()) {
                    parcelfiledescriptor out = context.getcontentresolver().openfiledescriptor(file.geturi(), "rw");
                    fd = out.getfiledescriptor();
                }
            } else {
                randomaccessfile file = null;
                try {
                    file = new randomaccessfile(destfile, "rws");
                    file.setlength(0);
                    fd = file.getfd();
                } catch (exception e){
                    e.printstacktrace();
                } finally {
                    if (file != null) {
                        try {
                            file.close();
                        } catch (ioexception e) {
                            e.printstacktrace();
                        }
                    }
                }
            }
        } catch (filenotfoundexception e) {
            e.printstacktrace();
        }
        return fd;
    }
 
    public static boolean savetreeuri(context context, string rootpath, uri uri) {
        documentfile file = documentfile.fromtreeuri(context, uri);
        if (file != null && file.canwrite()) {
            sharedpreferences perf = preferencemanager.getdefaultsharedpreferences(context);
            perf.edit().putstring(rootpath, uri.tostring()).apply();
            log.e(tag, "save uri" + rootpath);
            return true;
        } else {
            log.e(tag, "no write permission: " + rootpath);
        }
        return false;
    }
 
    /**
     * 返回true表示没有权限
     * @param context
     * @param rootpath
     * @return
     */
    public static boolean checkwritablerootpath(context context, string rootpath) {
        file root = new file(rootpath);
        if (!root.canwrite()) {
            log.e(tag,"sd card can not write:" + rootpath + ",is on extsdcard:" + documentsutils.isonextsdcard(root, context));
            if (documentsutils.isonextsdcard(root, context)) {
                documentfile documentfile = documentsutils.getdocumentfile(root, true, context);
                if (documentfile != null) {
                    log.i(tag, "get document file:" + documentfile.canwrite());
                }
                return documentfile == null || !documentfile.canwrite();
            } else {
                sharedpreferences perf = preferencemanager.getdefaultsharedpreferences(context);
                string documenturi = perf.getstring(rootpath, "");
                log.i(tag,"lum_2 get perf documenturi:" + documenturi);
                if (documenturi == null || documenturi.isempty()) {
                    return true;
                } else {
                    documentfile file = documentfile.fromtreeuri(context, uri.parse(documenturi));
                    if (file != null)
                        log.i(tag,"lum get perf documenturi:" + file.canwrite());
                    return !(file != null && file.canwrite());
                }
            }
        }else{
            log.e(tag,"sd card can write...");
        }
        return false;
    }
}

然后在app启动的地方检查下是否需要授权才能操作:

if (documentsutils.checkwritablerootpath(this, stringutils.storage_path)) {   //检查sd卡路径是否有 权限 没有显示dialog
      showopendocumenttree();
} 
 
 
private void showopendocumenttree() {
        log.e("showopendocumenttree", "start check sd card...");
        intent intent = null;
        if (android.os.build.version.sdk_int >= android.os.build.version_codes.n) {
            storagemanager sm = getsystemservice(storagemanager.class);
            storagevolume volume = sm.getstoragevolume(new file(stringutils.storage_path));
            if (volume != null) {
                intent = volume.createaccessintent(null);
            }
        }
        log.e("showopendocumenttree", "intent=" + intent);
        if (intent == null) {
            intent = new intent(intent.action_open_document_tree);
        }
        startactivityforresult(intent, documentsutils.open_document_tree_code);
    }
 
//................................
@override
    protected void onactivityresult(int requestcode, int resultcode, intent data) {
        switch (requestcode) {
            case documentsutils.open_document_tree_code:
                if (data != null && data.getdata() != null) {
                    uri uri = data.getdata();
                    documentsutils.savetreeuri(this, stringutils.storage_path, uri);
                    log.i(tag,"documentsutils.open_document_tree_code : "  + uri);
                }
                break;
        }
        super.onactivityresult(requestcode, resultcode, data);
    }
 

按以上代码,是可以实现对外置存储卡进行读和写操作了,只要机器没关机,多关打开关闭app,都不会弹下面这个授权框:

Android使用DocumentFile读写外置存储的问题

但是-----如果关机再重新开机,就要重新授权,这样很麻烦,用户体验也极其不好,所以又查询了很多资料,最后在*上找到办法,关键是下面这句:

granturipermission(getpackagename(), uri, intent.flag_grant_read_uri_permission | intent.flag_grant_write_uri_permission);
                    getcontentresolver().takepersistableuripermission(uri, intent.flag_grant_read_uri_permission | intent.flag_grant_write_uri_permission);

是在activityresult回调里,添加上面这两行代码,就不用每次都弹授权,影响体验了

Android使用DocumentFile读写外置存储的问题

到此这篇关于android使用documentfile读写外置存储的问题的文章就介绍到这了,更多相关android documentfile读写外置存储内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!