Android java gets sd card package name path

this test is ok

   File externalFilesDir = getExternalFilesDir(null);
        if (externalFilesDir != null) {
            String appFolderPathOnSdCard = externalFilesDir.getAbsolutePath();
        }

This one doesn't work sometimes:

    public static File getSDRootPath(Context context) {
        File sdPath;
        boolean isSDExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); //SD卡是否存在
        if (isSDExist) {
            if (Build.VERSION.SDK_INT >= 28) {
                File externalFileRootDir = context.getExternalFilesDir("");
                do {
                    externalFileRootDir = Objects.requireNonNull(externalFileRootDir).getParentFile();
                } while (Objects.requireNonNull(externalFileRootDir).getAbsolutePath().contains("/Android"));
                sdPath = Objects.requireNonNull(externalFileRootDir);
            } else {
                sdPath = context.getExternalFilesDir("");
            }
        } else {
            sdPath = Environment.getRootDirectory();//根目录
        }

        return sdPath;
    }

 File file=getSDRootPath(this);

Guess you like

Origin blog.csdn.net/jacke121/article/details/132506924