MediaFilePicker 总是显示空目录

MediaFilePicker is always showing empty directory

我刚刚复制了下面的代码片段并注释了路径和根路径。而且总是显示空目录,如下图。

MaterialFilePicker()
    .withActivity(this)
    .withCloseMenu(true)
    //.withPath(alarmsFolder.absolutePath)
    //.withRootPath(externalStorage.absolutePath)
    .withHiddenFiles(true)
    .withFilter(Pattern.compile(".*\.(jpg|jpeg)$"))
    .withFilterDirectories(false)
    .withTitle("Sample title")
    .withRequestCode(FILE_PICKER_REQUEST_CODE)
    .start()

下面我也试过了,但是不行

            .withPath(Environment.getExternalStorageDirectory().getPath())
            .withRootPath(Environment.getExternalStorageDirectory().getPath())

这是一个权限问题。您必须在 运行 时间添加权限。下面的代码片段无需任何修改即可正常工作。

private fun checkPermissionsAndOpenFilePicker() {
        val permissionGranted = ContextCompat.checkSelfPermission(
            requireContext(),
            Manifest.permission.READ_EXTERNAL_STORAGE
        ) == PackageManager.PERMISSION_GRANTED

        if (permissionGranted) {
            openFilePicker()
        } else {
            if (shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                showError()
            } else {
                requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), PERMISSIONS_REQUEST_CODE)
            }
        }
    }

    private fun showError() {
        Toast.makeText(
            context,
            "Allow external storage reading",
            Toast.LENGTH_SHORT
        ).show()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        if (requestCode == PERMISSIONS_REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults.first() == PackageManager.PERMISSION_GRANTED) {
                openFilePicker()
            } else {
                showError()
            }
        }
    }

    private fun openFilePicker() {
        MaterialFilePicker()
            .withSupportFragment(this)
            .withRequestCode(FILE_PICKER_REQUEST_CODE)
            .withHiddenFiles(true)
            .withFilter(Pattern.compile(".*\.(jpg)$"))
            .start()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == FILE_PICKER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            data ?: throw IllegalArgumentException("data must not be null")

            val path = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH)

            if (path != null) {
                Log.d("Path (fragment): ", path)
                Toast.makeText(
                    context,
                    "Picked file in fragment: $path", Toast.LENGTH_LONG
                ).show()
            }
        }
    }

    companion object {
        private const val PERMISSIONS_REQUEST_CODE = 0
        private const val FILE_PICKER_REQUEST_CODE = 1
    }