如何在 Kotlin Jetpack Compose 中使用 rememberLauncherForActivityResult 读取文件?

时间:2021-06-19 10:53:53

标签: android kotlin android-jetpack android-jetpack-compose

所以我有这个可组合的,它试图从存储中读取数据,

@Composable
private fun Screen() {
    val launcher = rememberLauncherForActivityResult(contract = ActivityResultContracts.StartActivityForResult()) { result ->
        val uri = result.data?.data.toString()
        if(uri !== null) {
            val file = File(uri)
            val bytes = file.readBytes()
            println(bytes)
        }
    }
    Column() {
        Button(onClick = {
            val intent = Intent().setType("*/*").setAction(Intent.ACTION_OPEN_DOCUMENT)
            launcher.launch(intent)
        }) {
            Text("Open file")
        }
    }
}

但是,它给了我这个错误:content:/com.android.providers.downloads.documents/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2FIMG_CEFEFF486A8C-1.jpeg: open failed: ENOENT (No such file or directory)。我在这里做错了什么?请帮忙。

1 个答案:

答案 0 :(得分:0)

想通了,

"dependencies": {
    "@testing-library/jest-dom": "^5.12.0",
    "@testing-library/react": "^11.2.6",
    "@testing-library/user-event": "^12.8.3",
    "@types/jest": "^26.0.23",
    "@types/node": "^12.20.11",
    "@types/react": "^17.0.4",
    "@types/react-dom": "^17.0.3",
    "bootstrap": "^5.0.0",
    "moment": "^2.29.1",
    "node-sass": "^5.0.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-moment": "^1.1.1",
    "react-scripts": "4.0.3",
    "typescript": "^4.2.4",
    "web-vitals": "^1.1.1"
  },