Flutter Android -从Intent检索文件

ar7v8xwq  于 2023-04-07  发布在  Flutter
关注(0)|答案(1)|浏览(121)

您好,我已经为我的Flutter应用程序注册了自定义文件扩展名。
当我点击一个带有此自定义扩展名的文件时,我的应用程序将打开。现在我将像这样访问检索到的文件:

override fun onCreate(savedInstanceState: Bundle?) {
   super.onCreate(savedInstanceState)
   handleOpenFileUrl(intent)
}

override fun onNewIntent(intent: Intent) {
   super.onNewIntent(intent)
   handleOpenFileUrl(intent)
}

private fun handleOpenFileUrl(intent: Intent?) {
   val p = intent?.data?.path
   if (p != null) intentPath = p;
}

现在我面临着这些问题:

  1. intentPath有时解析为"/device_storage/0/Documents/...",有时解析为"/external/file/<random number>"
    1.如何在Flutter应用中检索文件并读取其内容?
toe95027

toe950271#

我终于找到了解决办法:
你必须使用ContentResolver来获取文件的InputStream,并将其临时保存到该高速缓存目录:

private fun handleOpenFileUrl(intent: Intent?) {
    val uri: Uri? = intent?.data
    if (uri == null) return

    var fos: FileOutputStream? = null
    val path = context.cacheDir.absolutePath + "/" + System.currentTimeMillis() + ".themis"
    val file = File(path)
    if (!file.exists()) {
      file.parentFile?.mkdirs()
      try {
        fos = FileOutputStream(path)
        try {
          val out = BufferedOutputStream(fos)
          val `in`: InputStream = context.contentResolver.openInputStream(uri) ?: return
          val buffer = ByteArray(8192)
          var len = 0
          while (`in`.read(buffer).also { len = it } >= 0) {
            out.write(buffer, 0, len)
          }
          out.flush()
        } finally {
          fos.fd.sync()
        }
        openFileUrl = file.path;
      } catch (e: java.lang.Exception) {
        try {
          fos?.close()
        } catch (ex: IOException) {
        } catch (ex: NullPointerException) {
        }
      }
    }
  }

使用openFileUrl,您可以在Flutter应用程序中访问该文件。

相关问题