Android11的data目录,记录Android/data目录访问

公司APP要从/Android/data/com.tencent.mm/MicroMsg/Download选择文件上传,因为Android11权限问题,不让访问/Android/data了,网上搜了解决方案,这里记录一下
首先是请求权限

public void startForRoot() {
        Uri uri1 = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata");
        String uri = changeToUri(Environment.getExternalStorageDirectory().getPath());
        uri = uri + "/document/primary%3A" + Environment.getExternalStorageDirectory().getPath().replace("/storage/emulated/0/", "").replace("/", "%2F");
        Uri parse = Uri.parse(uri);
        DocumentFile documentFile = DocumentFile.fromTreeUri(this, uri1);
        Intent intent1 = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        intent1.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
                | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
        intent1.putExtra(DocumentsContract.EXTRA_INITIAL_URI, documentFile.getUri());
        startActivityForResult(intent1, 20);
    }

网上找的,没什么说的


允许访问data文件

允许访问好了,然后在权限请求返回中保存该权限,下次访问就不需要再请求了

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 20 && data != null){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                Uri uri = data.getData();
                //这个是保存权限的
                getContentResolver().takePersistableUriPermission(uri, data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION));//关键是这里,这个就是保存这个目录的访问权限
            }
            //本地存一下,用于判断是否已有访问权限
            SPUtils.putInt(mContext, ExamConstant.ANDROID_DATA, 1);
            //扫描文件夹
            scanFile();
        }
    }

扫描文件之后通过路径拼接拿到完整路径

//大概这样,伪代码
DocumentFile file ;;;
String path = "/Android/data/com.tencent.mm/MicroMsg/Download/" + file.getName()

但是这个路径在Android11里是会文件找不到,无法上传,没有吊用,还是权限问题,但是这个文件呢可以通过getContentResolver().openInputStream(Uri)开数据流,这样就可以复制文件操作了,如下:

//文件处理嘛,要在子线程,自己处理
try {
                    InputStream inputStream = mContext.getContentResolver().openInputStream(pathUri.getUri());
                    String path = pathUri.getPath();
                    int i = path.lastIndexOf("/") + 1;
                    String substring = path.substring(i);
                    String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Tineco/";
                    File directory = new File(savePath);
                    if (!directory.exists()) {
                        directory.mkdir();
                    }
                    File file = new File(savePath, substring);
                    FileOutputStream fos = new FileOutputStream(file);
                    long sum = 0;
                    byte[] buf = new byte[2048];
                    int len = 0;
                    while ((len = inputStream.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                    }
                    fos.flush();
                    ToolAlert.closeLoading();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = getIntent();
                            intent.putExtra("path", file.getAbsolutePath());
                            setResult(30, intent);
                            finish();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
//class PathUri 这个就是自己的类,主要保存路径或文件名和DocumentFile文件的Uri 
// private String path;
  //private Uri uri;
就是这个 InputStream inputStream = mContext.getContentResolver().openInputStream(uri);开流就可以读文件来复制了,当复制到其他非Android/data目录就可以操作文件上传了

这没什么复杂的,就是下面这个我也不会。。。就瞎写,就是通过DocumentFile.fromTreeUri()拿到对应文件夹,找到文件列表,通过流来复制出来该文件即可

File downloadFile = new File(mPath);
            DocumentFile doucmentFile = getDoucmentFile(mContext, downloadFile.getAbsolutePath());
            //不知道哪里写的不对,不能通过DocumentFile.fromTreeUri直接到Download目录,所以手动循环到该目录,
            //DocumentFile.fromTreeUri 返回的是TreeDocumentFile,拥有listFiles()方法,
            //而DocumentFile.fromSingleUri 返回的是SingleDocumentFile, 该类的listFiles(),源码里直接抛异常
            //     public DocumentFile[] listFiles() {
            //        throw new UnsupportedOperationException();
            //    }
            try {
                if (doucmentFile.isDirectory()){
                    DocumentFile[] documentFiles = doucmentFile.listFiles();
                    DocumentFile documentFile2 = null;
                    for (DocumentFile file : documentFiles) {
                        if (file.getName().equals("com.tencent.mm")){
                            documentFile2 = file;
                            break;
                        }
                    }
                    DocumentFile documentFile3 = null;
                    for (DocumentFile listFile : documentFile2.listFiles()) {
                        if (listFile.getName().equals("MicroMsg")){
                            documentFile3 = listFile;
                            break;
                        }
                    }
                    DocumentFile documentFile4 = null;
                    for (DocumentFile listFile : documentFile3.listFiles()) {
                        if (listFile.getName().equals("Download")){
                            documentFile4 = listFile;
                            break;
                        }
                    }//此时的documentFile4 才是download文件夹
                    for (DocumentFile filef : documentFile4.listFiles()) {
                        if (filef.isFile()){
                            list.add(new PathUri(filef.getName(), filef.getUri(), filef.lastModified()));
                        }
                    }
                    list.sort(new Comparator() {
                        @Override
                        public int compare(PathUri o1, PathUri o2) {
                            return (int) (o1.getModifyTime() - o2.getModifyTime());
                        }
                    });
                }

            }catch (Exception e){
                e.printStackTrace();
            }

//根据路径获得document文件
    public static DocumentFile getDoucmentFile(Context context, String path) {
        if (path.endsWith("/")) {
            path = path.substring(0, path.length() - 1);
        }
        String path2 = path.replace("/storage/emulated/0/", "").replace("/", "%2F");
        return DocumentFile.fromTreeUri(context, Uri.parse("content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata/document/primary%3A" + path2));
    }

写的比较乱,总结一下,第一获取权限及保存权限,第二步拿到download目录,第三步通过流来复制文件到可以访问的其他目录

下面贴一下完整代码,写的挺low,业务部门的要求也低,能跑就行。。。如果你需要用到这个,请你一定优化一下,比如那里的取download目录,比如开子线程,比如文件复制等等,做一个合格的开发者,这里的解决办法来源于此文,感谢作者的无私分享参考来源


public class WechatFileActivity extends BaseActivityV2 {
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;

    private RecyclerViewAdapter adapter;
    private List list = new ArrayList<>();
    private boolean retry;

    @Override
    public int bindLayout() {
        return R.layout.act_wechat_file;
    }

    @Override
    public void initParams(Bundle parms) {

    }

    @Override
    public void initView(View view) {
        ButterKnife.bind(this);
        ToolAlert.loading(this, "加载中");
        if (SPUtils.getInt(mContext, ExamConstant.ANDROID_DATA) == 1){
            scanFile();
        } else {
            startForRoot();
        }
    }

    public void startForRoot() {
        Uri uri1 = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata");
        String uri = changeToUri(Environment.getExternalStorageDirectory().getPath());
        uri = uri + "/document/primary%3A" + Environment.getExternalStorageDirectory().getPath().replace("/storage/emulated/0/", "").replace("/", "%2F");
        Uri parse = Uri.parse(uri);
        DocumentFile documentFile = DocumentFile.fromTreeUri(this, uri1);
        Intent intent1 = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        intent1.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
                | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
        intent1.putExtra(DocumentsContract.EXTRA_INITIAL_URI, documentFile.getUri());
        startActivityForResult(intent1, 20);
    }

    public String changeToUri(String path) {
        if (path.endsWith("/")) {
            path = path.substring(0, path.length() - 1);
        }
        String path2 = path.replace("/storage/emulated/0/", "").replace("/", "%2F");
        return "content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata/document/primary%3A" + path2;
    }

    private void setRecyclerView() {
        ToolAlert.closeLoading();
        adapter = new RecyclerViewAdapter(mContext, list, R.layout.item_wechat_file) {
            @Override
            protected void bindViewHolder(RecyclerViewHolder holder, PathUri itemData, int position) {
                ImageView imageView = holder.getView(R.id.ivImage);
                HomeWorkUtils.showImage(itemData.getPath(), imageView);
                holder.setText(R.id.tvName, itemData.getPath());
            }
        };
        adapter.setOnItemClickListener(new RecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerViewHolder holder, Object itemData, int position) {
                PathUri pathUri = (PathUri) itemData;
                copyFileByUri(pathUri);
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
    }

    private void copyFileByUri(PathUri pathUri) {
        ToolAlert.loading(mContext, "正在处理文件");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    InputStream inputStream = mContext.getContentResolver().openInputStream(pathUri.getUri());
                    String path = pathUri.getPath();
                    int i = path.lastIndexOf("/") + 1;
                    String substring = path.substring(i);
                    String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Tineco/";
                    File directory = new File(savePath);
                    if (!directory.exists()) {
                        directory.mkdir();
                    }
                    File file = new File(savePath, substring);
                    FileOutputStream fos = new FileOutputStream(file);
                    long sum = 0;
                    byte[] buf = new byte[2048];
                    int len = 0;
                    while ((len = inputStream.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                    }
                    fos.flush();
                    ToolAlert.closeLoading();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = getIntent();
                            intent.putExtra("path", file.getAbsolutePath());
                            setResult(30, intent);
                            finish();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private String mPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.tencent.mm/MicroMsg/Download";
    private class ScanLargeFiles extends AsyncTask {

        OnScanLargeFilesListener mOnScanLargeFilesListener;

        public ScanLargeFiles(OnScanLargeFilesListener onActionListener) {
            mOnScanLargeFilesListener = onActionListener;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
        }

        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        protected String doInBackground(Void... params) {
            File downloadFile = new File(mPath);
            DocumentFile doucmentFile = getDoucmentFile(mContext, downloadFile.getAbsolutePath());
            //不知道哪里写的不对,不能通过DocumentFile.fromTreeUri直接到Download目录,所以手动循环到该目录,
            //DocumentFile.fromTreeUri 返回的是TreeDocumentFile,拥有listFiles()方法,
            //而DocumentFile.fromSingleUri 返回的是SingleDocumentFile, 该类的listFiles(),源码里直接抛异常
            //     public DocumentFile[] listFiles() {
            //        throw new UnsupportedOperationException();
            //    }
            try {
                if (doucmentFile.isDirectory()){
                    DocumentFile[] documentFiles = doucmentFile.listFiles();
                    DocumentFile documentFile2 = null;
                    for (DocumentFile file : documentFiles) {
                        if (file.getName().equals("com.tencent.mm")){
                            documentFile2 = file;
                            break;
                        }
                    }
                    DocumentFile documentFile3 = null;
                    for (DocumentFile listFile : documentFile2.listFiles()) {
                        if (listFile.getName().equals("MicroMsg")){
                            documentFile3 = listFile;
                            break;
                        }
                    }
                    DocumentFile documentFile4 = null;
                    for (DocumentFile listFile : documentFile3.listFiles()) {
                        if (listFile.getName().equals("Download")){
                            documentFile4 = listFile;
                            break;
                        }
                    }
                    for (DocumentFile filef : documentFile4.listFiles()) {
                        if (filef.isFile()){
                            list.add(new PathUri(filef.getName(), filef.getUri(), filef.lastModified()));
                        }
                    }
                    list.sort(new Comparator() {
                        @Override
                        public int compare(PathUri o1, PathUri o2) {
                            return (int) (o1.getModifyTime() - o2.getModifyTime());
                        }
                    });
                }

            }catch (Exception e){
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            if (mOnScanLargeFilesListener != null) {
                mOnScanLargeFilesListener.onScanCompleted();
            }
        }
    }

    public interface OnScanLargeFilesListener{
        void onScanCompleted();
    }

    //根据路径获得document文件
    public static DocumentFile getDoucmentFile(Context context, String path) {
        if (path.endsWith("/")) {
            path = path.substring(0, path.length() - 1);
        }
        String path2 = path.replace("/storage/emulated/0/", "").replace("/", "%2F");
        return DocumentFile.fromTreeUri(context, Uri.parse("content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata/document/primary%3A" + path2));
    }

    @Override
    public void initListener() {

    }

    @Override
    public void doBusiness(Context mContext) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 20 && data != null){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                Uri uri = data.getData();
                getContentResolver().takePersistableUriPermission(uri, data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION));//关键是这里,这个就是保存这个目录的访问权限
            }
            SPUtils.putInt(mContext, ExamConstant.ANDROID_DATA, 1);
            scanFile();
        }
    }

    private void scanFile(){
        ScanLargeFiles scanLargeFiles = new ScanLargeFiles(new OnScanLargeFilesListener() {
            @Override
            public void onScanCompleted() {
                if (list.size() == 0){
                    if (!retry){
                        startForRoot();
                    } else {
                        ToastUtils.showShortToast(mContext, "没有找到文件");
                    }
                } else {
                    setRecyclerView();
                }
            }
        });
        scanLargeFiles.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    @Override
    public void resume() {

    }

    @Override
    public void destroy() {

    }
这个是取到的微信download文件夹,如果用户点击了,就复制该文件,然后返给上个页面复制文件的path
微信download目录下文件

有没有人知道里怎么把两张图同一排显示,即两张图左右排列?

你可能感兴趣的:(Android11的data目录,记录Android/data目录访问)