When Android manually scans all files, txt, log, png and other files cannot be scanned?

 Problem background:

I want to scan all the txt files in the system, but in the txt folder, the displayed number of files is empty

 How to scan manually

    /**
     *
     * 手动扫描方法
     *
     * @param dirPath
     * @return
     */
    private List<File> getFiles(String dirPath) {
        List<File> fileList = new ArrayList<>();
        File dir = new File(dirPath);
        File[] files = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                LogUtils.INSTANCE.d("getFiles file: " + file);
                if (file.isDirectory()) {
                    // 如果是目录,则递归扫描
                    fileList.addAll(getFiles(file.getAbsolutePath()));
                } else {
                    // 如果是文件,则添加到列表中
                    fileList.add(file);
                }
            }
        }
        return fileList;
    }

//方法调用
//文件系统挂起
 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        //扫描特定文件
        //getFiles("/storage/emulated/0/jlc-oa-phone-helper/logs");
        // 扫描系统所有文件
    getFiles(Environment.getExternalStorageDirectory().getAbsolutePath());
   }

problem causes:

When accessing and reading external files after android 11, you need to add the MANAGE_EXTERANAL_STORGE permission, and jump to a specific interface to apply for this permission.
 

Solution

    <!--    读取文件-->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <!--    android 11访问和读写外部文件时,需要添加该权限,并且跳转特定界面开启该权限-->
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>

Dynamically apply for "all file access permissions"

    /**
     * 访问文件读写外部文件权限,需要去特定界面申请
     *
     * @param activity 界面
     */
    public static void requestFilePermission(Activity activity) {
        LogUtils.INSTANCE.e("requestPermission Build.VERSION.SDK_INT: " +Build.VERSION.SDK_INT);
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse(String.format("package:%s", activity.getPackageName())));
                activity.startActivityForResult(intent, Activity.RESULT_CANCELED);
            }
        } catch (Exception e) {
            LogUtils.INSTANCE.e("requestPermission Exception: " + e.getMessage());
        }
    }

actual effect

Problem Solving Demonstration

Create value, happy to share!

776147358

Guess you like

Origin blog.csdn.net/ly_xiamu/article/details/131191243