3

还有其他人发现范围存储几乎不可能工作吗?哈哈。

我一直在尝试了解如何允许用户授予我的应用程序对应用程序文件夹之外的文本文件的写入权限。(假设允许用户在其 Documents 文件夹中编辑文件的文本)。我已经MANAGE_EXTERNAL_STORAGE设置了所有权限,并且可以确认该应用程序具有权限。但还是每次我尝试

val fileDescriptor = context.contentResolver.openFileDescriptor(uri, "rwt")?.fileDescriptor

我得到了Illegal Argument: Media is read-only错误。

我的清单请求这三个权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

我也尝试过使用旧版存储:

<application
    android:allowBackup="true"
    android:requestLegacyExternalStorage="true"

但仍然遇到这个只读问题。

我错过了什么?

额外说明

我如何获取 URI:

view?.selectFileButton?.setOnClickListener {
            val intent =
                Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
                    addCategory(Intent.CATEGORY_OPENABLE)
                    type = "*/*"
                    flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or
                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                }
            startActivityForResult(Intent.createChooser(intent, "Select a file"), 111)
        }

接着

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == 111 && resultCode == AppCompatActivity.RESULT_OK && data != null) {
        val selectedFileUri = data.data;
        if (selectedFileUri != null) {
            viewModel.saveFilename(selectedFileUri.toString())
            val contentResolver = context!!.contentResolver
            val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or
                    Intent.FLAG_GRANT_WRITE_URI_PERMISSION
            contentResolver.takePersistableUriPermission(selectedFileUri, takeFlags)
            view?.fileName?.text = viewModel.filename
            //TODO("if we didn't get the permissions we needed, ask for permission or have the user select a different file")
        }
    }
}
4

3 回答 3

3

你可以试试下面的代码。这个对我有用。

class MainActivity : AppCompatActivity() {

    private lateinit var theTextOfFile: TextView
    private lateinit var inputText: EditText
    private lateinit var saveBtn: Button
    private lateinit var readBtn: Button
    private lateinit var deleteBtn: Button

    private lateinit var someText: String
    private val filename = "theFile.txt"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (!isPermissionGranted()) {
            val permissions = arrayOf(WRITE_EXTERNAL_STORAGE)
            for (i in permissions.indices) {
                requestPermission(permissions[i], i)
            }
        }

        theTextOfFile = findViewById(R.id.theTextOfFile)
        inputText = findViewById(R.id.inputText)
        saveBtn = findViewById(R.id.saveBtn)
        readBtn = findViewById(R.id.readBtn)
        deleteBtn = findViewById(R.id.deleteBtn)

        saveBtn.setOnClickListener { savingFunction() }
        deleteBtn.setOnClickListener { deleteFunction() }
        readBtn.setOnClickListener {
            theTextOfFile.text = readFile()
        }

    }

    private fun readFile() : String{
        val rootPath = "/storage/emulated/0/Download/"
        val myFile = File(rootPath, filename)
        return if (myFile.exists()) {
            FileInputStream(myFile).bufferedReader().use { it.readText() }
        }
        else "no file"
    }

    private fun deleteFunction(){
        val rootPath = "/storage/emulated/0/Download/"
        val myFile = File(rootPath, filename)
        if (myFile.exists()) {
            myFile.delete()
        }
    }

    private fun savingFunction(){
        deleteFunction()
        someText = inputText.text.toString()
        val resolver = applicationContext.contentResolver
        val values = ContentValues()
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
            values.put(MediaStore.MediaColumns.DISPLAY_NAME, filename)
            values.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain")
            values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)
            val uri = resolver.insert(MediaStore.Files.getContentUri("external"), values)
            uri?.let { it ->
                resolver.openOutputStream(it).use {
                    // Write file
                    it?.write(someText.toByteArray(Charset.defaultCharset()))
                    it?.close()
                }
            }
        } else {
            val rootPath = "/storage/emulated/0/Download/"
            val myFile = File(rootPath, filename)
            val outputStream: FileOutputStream
            try {
                if (myFile.createNewFile()) {
                    outputStream = FileOutputStream(myFile, true)
                    outputStream.write(someText.toByteArray())
                    outputStream.flush()
                    outputStream.close()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }

        }
    }

    private fun isPermissionGranted(): Boolean {
        val permissionCheck = ActivityCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE)
        return permissionCheck == PackageManager.PERMISSION_GRANTED
    }

    private fun requestPermission(permission: String, requestCode: Int) {
        ActivityCompat.requestPermissions(this, arrayOf(permission), requestCode)
    }
}
于 2020-12-12T12:00:30.550 回答
1

就您的代码而言:

  • 您列出的所有权限都与此无关ACTION_OPEN_DOCUMENT
  • 你的旗帜都不Intent属于那里

但是,您真正的问题是您似乎在选择媒体,例如从“音频”类别中选择。ACTION_OPEN_DOCUMENT保证我们可以从 标识的内容中读取Uri,但不保证可写位置。不幸的是,MediaProvider阻止所有写访问,抛出您引用的消息的异常。

引用我去年提交的问题

问题是我们无法指定ACTION_OPEN_DOCUMENT Intent我们打算写的内容,因此希望将用户限制在可写位置。鉴于 Android Q/R 更加强调我们迁移到存储访问框架,因此需要这种功能。否则,我们只能检测到我们没有写权限(例如,DocumentFilecanWrite()),然后告诉用户“对不起,我不能在那里写”,这会导致糟糕的用户体验。

我在这篇博文中写了更多关于这个问题的内容。

因此,使用DocumentFileandcanWrite()查看是否允许您写入 标识的位置Uri,并要求用户选择不同的文档。

于 2020-10-03T23:11:54.873 回答
0

On Android 11 and testing with API 30 emulators i found public folders like

Download, Documents, DCIM, Alarms, Pictures and such 

writable for my apps using classic file system paths.

Restricted to app's own files.

Further i found that files created by one app in this way were writeble by a different app using SAF.

于 2020-10-04T08:30:01.077 回答